I have a file in blob storage that is in .xslx format and I am trying to convert it to .csv format using Syncfusion.XlsIO Nuget package.
I have tried the following:
private async Task ConvertExcelToCsv()
{
var fileName = await _fileStore.GetContainerFileAsync(AppSettingsConstants.FileNames.Container, "myfile.xlsx");
using (ExcelEngine excelEngine = new ExcelEngine())
{
var application = excelEngine.Excel;
var workbook = application.Workbooks.Open(fileName.Name);
var worksheet = workbook.Worksheets[1];
worksheet.SaveAs("myfile.csv", ",");
}
}
When I debug, the fileName is retrieved successfully, but the application breaks on using (ExcelEngine excelEngine = new ExcelEngine()) with a NullReferenceException error.
Where am I going wrong here?
The way you can do it is defined here: https://www.syncfusion.com/kb/9098/how-to-export-excel-data-to-csv-file
Most likely, you would need to install from NuGet not only Syncfusion.XlsIO.WinForms , but also System.Drawing.Common and System.Security.Permissions.
This code worked:
try
{
//Initialize ExcelEngine
using (ExcelEngine excelEngine = new ExcelEngine())
{
//Initialize Application
IApplication application = excelEngine.Excel;
//Set default version for application
application.DefaultVersion = ExcelVersion.Excel2013;
//Open a workbook to be export as CSV
IWorkbook workbook = application.Workbooks.Open(#"E:\Users\Public\Documents\" + "ExcelFile.xlsx");
//Accessing first worksheet in the workbook
IWorksheet worksheet = workbook.Worksheets[0];
//Save the workbook to csv format
worksheet.SaveAs("Output.csv", ",");
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
throw;
}
Make sure you have permission to access the Excel file. Usually, it helps if you test it with files which are saved on another drive than on which Windows is installed (e.g. E:\, if Windows is on C:\).
Thank you, it turned out I was missing a reference to System.Drawing nuget
Related
is there a way to export information to an xlsm file? the steps I do is:
in a button I put an input to select the file, I upload the file to the server
I look for the sheet which is already specified in the code
I modify the file information according to the information to be exported
command to save the file locally.
the error is as follows:
{"The 'br' start tag on line 59 position 30 does not match the end tag of 'font'. Line 60, position 9."}
when indicating the sheet with which to work
I share my code: any suggestions?
public void ExportFile(string FileName, string UserID)
{
FileInfo fi = new FileInfo(FileName);
Master.MSGError = string.Empty;
string SheetName = "test";
using (MemoryStream file = new MemoryStream())
{
try
{
using (ExcelPackage xlPackage = new ExcelPackage(fi))
{
ExcelWorksheet worksheet;
worksheet = xlPackage.Workbook.Worksheets[SheetName]; //here is the error exception
worksheet.Cells[1, 1].Value = "TEST";
//save file
xlPackage.SaveAs(file);
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.BinaryWrite(file.ToArray());
Response.Flush();
Response.End();
}
}
catch (Exception ex)
{
Master.fc.MSGError = ex.Message;
}
}
}
Currently I solved my problem I thought that the detail was in the macro, but I found the real error doing different tests, it seems that both epplus and closedxml have problems reading certain information in the excel, I ended up using closedxml and applying the solution:
OpenXml Excel: throw error in any word after mail address
I'm sorry for confusion
I use the Open from the Assets on xamarin then and i Open on the Workbooks when i build my app it stoped working but if i coding on normal Console it's working, What i forget ?
var asset = Application.Context.Assets.Open("test.xlsx");
new ExcelEngine().Excel.Workbooks.Open(asset);
https://help.syncfusion.com/file-formats/xlsio/create-read-edit-excel-files-in-xamarin-c-sharp
In Android, you could try the code below.
string filePath="test.xlsx";
using (ExcelEngine excelEngine = new ExcelEngine())
{
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2016;
var asset = Android.App.Application.Context.Assets.Open(filePath);
using (StreamReader sr = new StreamReader(asset))
{
var inputStream = sr.BaseStream;
//Open the Tab delimited CSV file
IWorkbook workbook = application.Workbooks.Open(inputStream, "\t");
IWorksheet sheet = workbook.Worksheets[0];
var s = sheet.Columns.Count();
}
}
The code works well on my side to get the Column count of the Excel.
If you want to use this in Xamarin.Forms, you could use the Dependency Service. https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/dependency-service/introduction
i'am trying to get an xls file from an ZipArchive but cant get it with EPPLUS
foreach (ZipArchiveEntry entry in archive.Entries)
{
if (entry != null)
{
string filepath = entry.FullName;
FileInfo fileInfo = new FileInfo(filepath);
//here i got the excel package with the xls file inside the excelPackage
using (ExcelPackage excelPackage = new ExcelPackage(fileInfo))
{
//but here impossible de get the worksheet or workbook inside or anything else
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.FirstOrDefault();
int totalColomn = worksheet.Dimension.End.Column;
int nbrsheet = excelPackage.Workbook.Worksheets.Count();
}
}
}
the ExcelPackage i get in debug
i see the xls file on debug inside the excelpackage but just when i try to get worksheet it exit without exception code....
same here when trying with entryStream
using (var entryStream = entry.Open())
{
//Cant even get the excelpackage, it crash here without exception
using (ExcelPackage excelPackage = new ExcelPackage(entryStream))
{
ExcelWorksheet worksheetest = excelPackage.Workbook.Worksheets.FirstOrDefault();
}
}
the stream here seem also strange ...
entryStream Debug
Working with .NET CORE Blazor ServerSide, ePPLUS 4.5
Thanks for helping
entry.FullName refers to the full path to the file inside the zip archive, while FileInfo describes a file in the filesystem of the OS, which is a completely different thing. You haven't extracted anything to the OS filesystem yet, so the FileInfo won't refer to a file that actually exists.
Try the ExcelPackage constructor that takes a Stream, which you can get directly from a ZipArchiveEntry:
using (var entryStream = entry.Open())
{
using (ExcelPackage excelPackage = new ExcelPackage(entryStream))
{
// ...
}
}
I find the problem.
it was that i tried to get an xls file and the epplus library dont work with it...
you have to be careful, EPplus dont work with xls file
So , your solution Jeff is working, it was my fault, didn't specified the extension of my excel file... sorry
-> EPlus with an .xlsx OK, not .xls
My bad.
Thanks anyway :-)
I have a XSLT transformed HTML data in MemoryStream (in C#). I am trying to convert this to an Excel format before emailing, preferably conversion happens all in memory again without saving to local disk. I can worry about the email attachment part later. Can anyone point me to a sample on how I could do the conversion from HTML to Excel format either through OpenXML or with Office.Interop.Excel.
The HTML data is well formed and I could manually do the conversion by opening the html in Excel application and do a Save As to save it in xlsx format (Office 2010), no problem. I also tried to simply change the .html extension to .xlsx, but then excel complains about opening it.
What's the best way to automate the manual SaveAs action so that I could use the same html data in Excel format? I understand that I could create a separate .xslt for directly converting my XML into Excel format. But, that'll be too many .xslt to maintain. I'm trying to find the hack to let Excel do the work for me.
Thank you for any and all pointers in advance!
EDIT:
I figured I have no choice but to store html to disk and read it back and use Excel Interop to do SaveAs method. When I did try though, getting the exception with HRESULT: 0x800A03EC on the SaveAs method. Here's how to reproduce it.
steps to reproduce the behavior
Save this text
<html><head></head><body><center><h1>Test Header</h1></center></body></html>
as C:\Test.html
after making reference to Excel interop like this,
using Excel = Microsoft.Office.Interop.Excel;
Try this code
`
var app = new Excel.Application();
Excel.Workbook wb = null;
try
{
wb = app.Workbooks.Open(#"c:\test.html");
wb.SaveAs(#"c:\test.xlsx", Excel.XlFileFormat.xlOpenDocumentSpreadsheet);
//wb.SaveCopyAs(#"c:\test.xlsx");
wb.Close();
}
catch (Exception ex)
{
//_logger.Error(ex);
}
finally
{
app.Quit();
}
`
I always get the mentioned exception on SaveAs no matter which fileformat I choose or even not mentioning the fileformat there..
Any ideas?
This code works. It turns out the exception I was getting is only related to the file format I was trying to save. When I changed it to Open XML workbook, it saved fine.
using Excel = Microsoft.Office.Interop.Excel;
.
.
.
var app = new Excel.Application();
Excel.Workbook wb = null;
try
{
wb = app.Workbooks.Open(#"c:\test.html");
wb.SaveAs(#"c:\test.xlsx", Excel.XlFileFormat.xlOpenXMLWorkbook);
//wb.SaveCopyAs(#"c:\test.xlsx");
wb.Close();
}
catch (Exception ex)
{
//_logger.Error(ex);
}
finally
{
app.Quit();
}
Here's the updated code that takes bytes[] html as input and returns xlsx in bytes[]
public static byte[] DoConvertXlDataToOpenXml(byte[] data, FileInfo fileInfo)
{
ExcelInterop.Application excelApp = null;
ExcelInterop.Workbooks workBooks = null;
ExcelInterop.Workbook workBook = null;
FileInfo tempFile = null;
FileInfo convertedTempFile = null;
try
{
//Stream the file to temporary location, overwrite if exists
tempFile = new FileInfo(Path.ChangeExtension(Path.Combine(Path.GetTempFileName()), fileInfo.Extension));
using (var destStream = new FileStream(tempFile.FullName, FileMode.Create, FileAccess.Write))
{
destStream.Write(data, 0, data.Length);
}
//open original
excelApp = new ExcelInterop.Application();
excelApp.Visible = false;
excelApp.DisplayAlerts = false;
workBooks = excelApp.Workbooks;
workBook = workBooks.Open(tempFile.FullName);
convertedTempFile = new FileInfo(Path.ChangeExtension(Path.GetTempFileName(), "XLSX"));
//Save as XLSX
excelApp.Application.ActiveWorkbook.SaveAs(
convertedTempFile.FullName
, Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook
, ConflictResolution: ExcelInterop.XlSaveConflictResolution.xlLocalSessionChanges);
excelApp.Application.ActiveWorkbook.Close();
return File.ReadAllBytes(convertedTempFile.FullName);
}
catch (Exception)
{
throw;
}
finally
{
if (workBooks != null)
Marshal.ReleaseComObject(workBooks);
if (workBook != null)
Marshal.ReleaseComObject(workBook);
if (excelApp != null)
Marshal.ReleaseComObject(excelApp);
if (tempFile != null && tempFile.Exists)
tempFile.Delete();
if (convertedTempFile != null && convertedTempFile.Exists)
{
convertedTempFile.Delete();
}
}
}
When I trying open secured document I have this exception
System.Exception : Can not open the package. Package is an OLE compound document. If this is an encrypted package, please supply the password
I write this hard method for test
public bool HasPassword()
{
try
{
if(File.Exists(FileName))
{
var fileStream = File.Open(FileName, FileMode.Append);
var package = new ExcelPackage();
package.Load(fileStream);
}
}
catch(Exception)
{
return true;
}
return false;
}
but I think that it is wrong approach.
How to check whether it is password-protected excel file ?
If EEPlus isn't mandatory you can simply use the Workbook.HasPassword property.
Workbook book = ****xyz****;
if (book.HasPassword)
{
book.Password = Properties.Settings.Default.ExcelFilePW;
MessageBox.Show("Excel file is encrpyted");
}
Therefore you need to create a reference to the Office Interop Excel component which can be found in .NET / COM (sometimes).
Then just embed it in your project with the using directive.