How to process an iFormFile with ClosedXML with c# - c#

I want to load an excel file into XLWorkbook
using var workbook = new XLWorkbook("iFormFile needs to go here");
var ws = workbook.Worksheet(1);

There can be better answers than this, but this should work.
using var workbook = new XLWorkbook(iFormFile.OpenReadStream());
var ws = workbook.Worksheet(1);

Related

ClosedXML: C# Excel Import auto format Excel file

I am working with closedXML in C#. I'm importing an Excel. It is importing correct data but auto-format rows and headers every time. I need to compare data of Excel file in C# with a standard template. Due to formatting, it doesn't match. Can somebody help me to remove theme/ autoformat from Excel in C#?
DataTable dt = _excecuteProcedure.ToDataTable(filteredAmenities);
using(XLWorkbook wb = new XLWorkbook())
{
var ws = wb.Worksheets.Add(dt);
ws.Tables.FirstOrDefault().ShowAutoFilter = false;
ws.Name = "Sheet1";
using(MemoryStream stream = new MemoryStream())
{
wb.SaveAs(stream);
return File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Template.xlsx");
}
}

Read Excel file from memory stream in C# Console application

I am fetching an Excel file from ftp and getting that file in a memory stream. I have to read that file from memory stream. I tried through Excel Interop but it is not accepting memory stream as a parameter in
xlWorkBook = xlApp.Workbooks.Open(strm, 0, true, 5, "", "", true,
Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
According to system requirement that I cannot save that file temporary; because I am using Azure web jobs for Console application deployment. Is there any way to read file from memory stream or can I convert that memory stream into an array of string?
I can suggest you to use ExcelDataReader 3.1.0 to read data from an Excel file.
Now you can use that MemoryStream in ExcelReader like this:
Note that reader of old Excel files -.xls- is different form newer files -.xlsx-.
var excelReader = originalFileName.EndsWith(".xls")
? ExcelReaderFactory.CreateBinaryReader(stream)
: ExcelReaderFactory.CreateOpenXmlReader(stream);
If you want to extract a string from your MemoryStream you can use a StreamReader:
var streamReader = new StreamReader(memoryStream);
var stringResult = streamReader.ReadToEnd();
If you want to work over a FileStream you can copy your MemoryStream to it like this:
memoryStream.CopyTo(fileStream);
Also EasyXLS accepts streams, including MemoryStream.
I don't know if you need only data in cells from Excel, or other information, but the code bellow is only for data:
ExcelDocument excelWorkbook = new ExcelDocument();
DataSet ds = excelWorkbook.easy_ReadXLSActiveSheet_AsDataSet(memoryStream);
More details about reading Excels, you can find at this location:
https://www.easyxls.com/manual/FAQ/read-excel-file-in-dot-net.html
There is no MS Office present in the Azure Webjob, so we cannot use Microsoft.Office.Interop Dll in the Azure Webjob. Please have a try to use DocumentFormat.OpenXml to do that. The following is the demo code from the official document. I also find another tutorials about how to Read and Write Microsoft Excel with Open XML SDK.
public static void OpenAndAddToSpreadsheetStream(Stream stream)
{
// Open a SpreadsheetDocument based on a stream.
SpreadsheetDocument spreadsheetDocument =
SpreadsheetDocument.Open(stream, true);
// Add a new worksheet.
WorksheetPart newWorksheetPart = spreadsheetDocument.WorkbookPart.AddNewPart<WorksheetPart>();
newWorksheetPart.Worksheet = new Worksheet(new SheetData());
newWorksheetPart.Worksheet.Save();
Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>();
string relationshipId = spreadsheetDocument.WorkbookPart.GetIdOfPart(newWorksheetPart);
// Get a unique ID for the new worksheet.
uint sheetId = 1;
if (sheets.Elements<Sheet>().Count() > 0)
{
sheetId = sheets.Elements<Sheet>().Select(s => s.SheetId.Value).Max() + 1;
}
// Give the new worksheet a name.
string sheetName = "Sheet" + sheetId;
// Append the new worksheet and associate it with the workbook.
Sheet sheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = sheetName };
sheets.Append(sheet);
spreadsheetDocument.WorkbookPart.Workbook.Save();
// Close the document handle.
spreadsheetDocument.Close();
// Caller must close the stream.
}

Exporting large(>500000 rows) Datasets into xlsx

I have problem with export dataset into xlsx. My code:
DataSet freeTable = new DataSet();
freeTable = FoxDal.Instance.freeTable;
XLWorkbook wb = new XLWorkbook();
wb.Worksheets.Add(freeTable.Tables[0], "sheet1");
wb.SaveAs(#"E:\test5.xlsx");
While running code VS give's me prompt ( asking me where is XLReentrantEnumerableSet.cs) if i dont choose it VS throw exception System.OutOfMemoryException. Im using ClosedXML. There are some attached libraries for this framework? With small tables my code working corectly.
I change framework to EPPlus and now i can convert large files.
My new code:
DataSet freeTable = new DataSet();
freeTable = FoxDal.Instance.freeTable;
FileInfo fileInfo = new FileInfo(#"E:\Test.xlsx");
using (ExcelPackage pck = new ExcelPackage())
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("table");
ws.Cells["A1"].LoadFromDataTable(freeTable.Tables[0], true);
pck.SaveAs(fileInfo);
}

Updating the excelsheet using EPPlus in c#

I have a excel file which contains sheet named Data. This sheet already contains few data. I need to open this file and add more data in it. I have tried searching about this but everyone is just creating new sheets in their workbook. I need to update the current sheet. Below is my code:
MemoryStream ms = new MemoryStream();
using (FileStream fs = File.OpenRead(#"Path\File.xlsx")
using (ExcelPackage excelPackage = new ExcelPackage(fs))
{
ExcelWorkbook excelWorkBook = excelPackage.Workbook;
ExcelWorksheet excelWorksheet = excelWorkBook.Worksheets.First();
excelWorksheet.Cells[1, 1].Value = "Test";
excelWorksheet.Cells[3, 2].Value = "Test2";
excelWorksheet.Cells[3, 3].Value = "Test3";
excelPackage.SaveAs(ms);
}
but it didnt update the sheet. I do not what I am doing wrong. Can anyone help me please. Thanks
You are doing this:
Create a MemoryStream object in memory to store binary data.
Open file and read it into the MemoryStream object.
Create an ExcelPackage object based on the data in the MemoryStream object.
Make changes to the spreadsheet.
Save changes back to the MemoryStream object.
That's why the spreadsheet file does not get updated.
Use FileInfo and open the file directly with ExcelPackage:
// using System.IO;
FileInfo file = new FileInfo(#"Path\File.xlsx");
using (ExcelPackage excelPackage = new ExcelPackage(file))
{
ExcelWorkbook excelWorkBook = excelPackage.Workbook;
ExcelWorksheet excelWorksheet = excelWorkBook.Worksheets.First();
excelWorksheet.Cells[1, 1].Value = "Test";
excelWorksheet.Cells[3, 2].Value = "Test2";
excelWorksheet.Cells[3, 3].Value = "Test3";
excelPackage.Save();
}
Try this
var file = new FileInfo(path);
if (file .Exists)
{
using (ExcelPackage excelPackage = new ExcelPackage(file))
{
ExcelWorksheet ws = excelPackage.Workbook.Worksheets.First();
ws.Cells[1,1].Value = "Test1";
excelPackage.Save();
}
}

Reading memory stream

I'm trying to create an excel file and make that available as download. But i have some trouble with the download part.
I'm using EPPlus to create an xml file. I've got that working. But just local. I'm not sure how to force the download of the file.
This is my code:
public Stream GetXlsxDocument(IQueryable data)
{
const string sheetName = "Sheet1";
var localFile = new FileInfo(#"C:\test2.xlsx");
var file = new FileInfo("test2.xlsx");
// Used for local creation
//ExcelPackage p = new ExcelPackage();
MemoryStream stream = new MemoryStream();
using (ExcelPackage p = new ExcelPackage(stream))
{
p.Workbook.Worksheets.Add("Sheet1");
ExcelWorksheet ws = p.Workbook.Worksheets[1];
ws.Name = sheetName;
ws.Cells.Style.Font.Size = 11;
ws.Cells.Style.Font.Name = "Calibri";
ws.SetValue(1, 1, "aaa"); // Test data
// Used for local creation
//p.SaveAs(localFile);
p.SaveAs(stream);
}
return stream;
}
Like i said before. Creating the xlsx file locally on my C:\ disk works. But how can i force the download of the created xlsx file?
Right now its giving me an xlsx file of 0 bytes. I'd need to return a stream which isn't empty. Anyone any idea how i can do this..??
rewind it:
stream.Position = 0;
return stream;

Categories