I'm writing a program to process some excel documents, the program is written in C# in Visual Studio 2010, and I'm using the NPOI library.
I notice the I was not able to use CloneSheet() for the xlsm file, but I was able to do so with xlsx.
CloneSheet() is a function that I really need for the process, so I really would like to get it working instead of copy everything cell by cell.
I thought of converting the file to xlsx. I was able to do it manually, but not programmatically.
This is the code I wrote to attempt to do so:
XSSFWorkbook workbook;
//read original xlsm file into workbook
using (FileStream file = new FileStream(#"OriginalFile\" + filename, FileMode.Open, FileAccess.Read))
{ workbook = new XSSFWorkbook(file); }
//change file extension to xlsx and save in a new location
filename = Path.ChangeExtension(filename, "xlsx");
if (!Directory.Exists("NewFile"))
Directory.CreateDirectory("NewFile");
FileStream stream = new FileStream(("NewFile\\New" + filename), FileMode.Create, System.IO.FileAccess.Write);
workbook.Write(stream);
stream.Close();
//read the newly created file from the new location
using (FileStream file = new FileStream(#"NewFile\\New" + filename, FileMode.Open, FileAccess.Read))
{ workbook = new XSSFWorkbook(file); }
The above code will create the new xlsx file, but the file cannot be open and seems to be corrupted...
I've been googling for a while and couldn't seem to find a solution, can anyone help or point me to the right direction?
--EDIT---
I tried a different method using Open XML I found here, but I have the same issue, where the file is created but I can't open the file.
However, the file doesn't seem to be corrupted. My program that is reading the file have no problem reading the data, and when I try to open the file in excel it's saying "The file is a macro-free file, but contains macro-enable content."
Seems like I'm getting closer, but I need to be able to open the output file otherwise it's no use....
You may have to roll your own method: iterate rows then cells. This post Copy Row Helper got me started. You'll have to modify it to use two workbooks. This method will copy data and formulas. CellStyles will have to be recreated as they they specific to the originating workbook.
Related
I'm loading data into excel template stored in server and downloading it using FileStreamResult. I want to download the excel as read only. To make read only as I tried path is asking but I don't know where the user can download it into his system from server. So, how can I make the file read only?
I'm able to download as read only but it was asking prompt like "Do you want save changes or open as Read-Only?" I don't want that prompt and file to be open directly with Read-Only.
I tried using macro
But it is asking prompt to save changes.
As I don't know the path as user will download from server to his particular location. So, how can I make that read Only without using path r filename?
Controller:
System.IO.Stream spreadsheetStream = new System.IO.MemoryStream();
XLWorkbook wb = new XLWorkbook(Server.MapPath("~/XlsReport/Report_Template.xlsm"));
.....(Loading data into worksheets)...
wb.SaveAs(spreadsheetStream);
spreadsheetStream.Position = 0;
return new FileStreamResult(spreadsheetStream,"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") { FileDownloadName = "Report.xlsm" };
Macro:
Private Sub Workbook_Open()
ThisWorkbook.ChangeFileAccess xlReadOnly
End Sub
The downloaded file is asking to save changes. It should be directly open as ReadOnly without any prompts.
I used
ThisWorkbook.Saved = True
ThisWorkbook.ChangeFileAccess xlReadOnly
Now the downloaded file was directly opening in read only.
I'm using the below method to check if a file is already in use... seems to work just fine but my problem is that if I have excel open, sometimes the filestream actually opens and leaves open the excel file that its currently checking.
Anyone know why the file is actually opening and not closing when it leaves the using statement?
EDIT: More to the above, it opens the excel file and then it display a message box telling me that the file is available to Read/Write
I put the below in the comments but I think it pertains to my usage of the IsFileLocked code and may actually be the real cause??
I'm using the IsFileLocked code along with a filewatcher. When the filewatcher goes off I check if the excel file is still in use and if its not in use then I query data back from that excel file.
Process.. 1.) Excel file has changed or is being changed by another user 2.) make sure its still not in use with the IsFileLocked method 3.) if file is no longer in use then query data back from the excel file but sometimes the excel file actually opens on the user's computer who is watching excel files for changes.. if this makes sense
protected virtual bool IsFileLocked(string path)
{
try
{
using (FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None))
{
}
}
catch (IOException)
{
//the file is unavailable because it is:
//still being written to
//or being processed by another thread
//or does not exist (has already been processed)
return true;
}
finally
{
}
//file is not locked
return false;
}
I am trying to open an .xlsx file using Npoi but it keeps crashing with the following error:
1 is not a supported code page.
Parameter name: codepage
My code is very simple:
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Excel Workbook|*.xlsx";
DialogResult dr = ofd.ShowDialog();
if (dr == DialogResult.OK)
{
XSSFWorkbook myWorkbook;
FileStream fs = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read);
using (fs)
{
myWorkbook = new XSSFWorkbook(ofd.FileName);
}
}
The error happens while trying to create the workbook. I tried also using the stream, such as:
myWorkbook = new XSSFWorkbook(fs);
Does anyone know what is wrong? I can't find a proper example on the net for dealing with .xlsx files. I am suing the latest build (2.0.1).
Thanks.
ICSharpCode.SharpZipLib.Zip.ZipConstants.DefaultCodePage = Encoding.Default.CodePage;
...
FileStream fs = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read);
XSSFWorkbook workbook = new XSSFWorkbook(fs);
it works for me... ;)
I have been using the Workbook Factory without issues. It will detect whether the file is xls or xlsx and return the appropriate object for you. Note that this is version 2.06.
A quick sample:
_fileStream = new FileStream(filenamePath, FileMode.Open, FileAccess.Read);
_currentWorksheet = _workbook.GetSheetAt(0);
_workbook = WorkbookFactory.Create(_fileStream);
_fileStream.Close();
I have been Apache POI user for the last decade and I thought that NPOI was as good as his Java father but I'm afraid TheGateKeeper is right: a long way to go.
I have to look for OpenXML :(
I was able to open the file successfully using EPPlus, another Excel library. I still use NPOI for .xls files but for .xlsx I think it has a long way to go.
Please try the latest NPOI version: NPOI 2.0 RC. Here is the link: https://npoi.codeplex.com/releases/view/112932
I have an excel .csv file that has some data in the below formats in cells:
NAME Address Contact
Shoeb Lko 675567
Rajesh Banaras 7687678
.csv file is not a text file having only .csv extension. It is a csv file that is made using Microsoft Excel file...For testing you can also make .csv file... For this (1) create an excel file (2) open this excel file (3) go to file menu and click on "save as" (4) select CSV(Comma Seperated) option in Save as type: ---- Now this is .csv file from which I will read content and write content also in a .csv file
I am trying to use C# to write another Excel .csv file in the same format.
Code that I am using is written below:
//Below line is reading file from system drive
StreamReader rd = new StreamReader("D:\FilesUploadedToTablet\drivers.csv", true);
//Below line is writing data to file existing in our site folder
StreamWriter wr = new StreamWriter(Server.MapPath(".") + "\filename\CSVFile.csv");
wr.Write(rd.ReadToEnd());
rd.Close();
wr.Close();
Here StreamReader is reading drivers.csv file but StreamWriter is not writing that content to the CSVFile.csv file. If I use any text file in place of .csv file then the content writes successfully. What am I doing wrong?
You could try using a BinaryReader() instead of the StreamReader(). Also try opening the StreamReader as follows:
StreamReader("D:\FilesUploadedToTablet\drivers.csv", false);
It looks like you are only copying the file, not filtering or performing any processing on it. Why not just use File.Copy:
File.Copy("D:\FilesUploadedToTablet\drivers.csv", Server.MapPath(".") + "\filename\CSVFile.csv");
Thanx all of you for suggesting me...
I got it's solution – Solution that I got is written below :
string csvContent = string.Empty;
if (File.Exists("SourceFilePath"))
{
StreamReader rd = new StreamReader("SourceFilePath", true);
csvContent = rd.ReadToEnd();
rd.Close();
var DestPath = HttpContext.Current.Server.MapPath("~/CSV Files/")+"MyFile.csv";
StreamWriter wr = new StreamWriter(DestPath, true);
StringBuilder sb = new StringBuilder(csvContent);
wr.WriteLine(sb.ToString());
sb.Clear();
wr.Close();
I am attempting to export data to a excel spreadsheet and so open that Excel spreadsheet using Visual Studio 2010 and Excel 2010 on Windows 7, but I get the following error.
'1.xls' cannot be accessed. The file may be corrupted, located on a server that is not responding, or read-only.
I have checked the file path and given Everyone full control of the file. Here is my code.
saveFileDialog1.FileName = "";
saveFileDialog1.Filter = "(Excel Files)|*.xls";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
System.IO.Stream st = new System.IO.FileStream(saveFileDialog1.FileName,
FileMode.Create,
FileAccess.Write,
FileShare.None);
this.gridEXExporter1.ExportMode = Janus.Windows.GridEX.ExportMode.AllRows;
gridEXExporter1.Export(st);
//////////////////////////////////////
///// Opening the Excel File
/////////////////////////////////////
Process.Start(saveFileDialog1.FileName);
Thanks in advance.
You probably have to close the output file before you try to open it using Excel. Call st.Close() before Process.Start.