Read Excel file from memory stream in C# Console application - c#

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.
}

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");
}
}

NotOLE2FileException was unhandled by user code. Invalid header signature. Cannot import .csv file in my asp.net application

I have a import functionality in my asp.net application where right now I am able to import only .xls files. I want to make the import functionality working so that it should import .csv file. But I am getting this errorsee the error
Can some one please help me in code, how can I import .csv file.
ImportHandler.cs
private IEnumerable<PermanentFlight> ExportPermanentFlightsXlToEf(string fileName)
{
Log.Info("Exporting records from Excel to PF Entity starts.");
HSSFWorkbook workBook;
using (var file = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
workBook = new HSSFWorkbook(file);
}
var workSheet = workBook.GetSheetAt(0);
var rowIdx = 1;
var scheduleName = string.Empty;
var list = new List<PermanentFlight>();

Copy sheet from one workbook to another using NPOI in C#

I need to copy a sheet from one workbook to another. I am trying with the below code, but it is not working:
ISheet newSheet = wb.GetSheetAt(0).CopySheet("WeeklyReport");
string filePath = "billing_template2.xlsx";
XSSFWorkbook billingWorkbook;
using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
billingWorkbook = new XSSFWorkbook(fs);
}
billingWorkbook.Add(newSheet);
where wb is the source workbook and billingWorkbook is my destination workbook.
Note: My destination workbook already had a sheet. I need to add the copied sheet after this one.

stream to excel without saving

I am creating excel and filling values into it. i am using EPPlus.
I can save it using filestream and open it.
but i want to open it without saving.
I thought we can use memorystream in some way to generate the excel directly.
Please guide.
try
{
MemoryStream newFile = new MemoryStream();
using (ExcelPackage package = new ExcelPackage(newFile))
{
// Add Data Collection worksheet
ExcelWorksheet dataWorksheet = package.Workbook.Worksheets.Add("Sheet1");
dataWorksheet.Cells[1, 1].Value = " My Text";
dataWorksheet.Cells[1, 1].Style.Font.Size = 14;
dataWorksheet.Cells[3, 1].Value = BALGlobalVariables.cocName;
dataWorksheet.Cells[5, 1].Value = "IR From Date :";
dataWorksheet.Cells[6, 1].Value = "IR To Date : ";
dataWorksheet.Cells[5, 6].Value = "From Date :";
dataWorksheet.Cells[6, 6].Value = "To Date : ";
dataWorksheet.Cells[5, 2].Value = fromDate;
dataWorksheet.Cells[6, 2].Value = toDate;
dataWorksheet.Cells[5, 7].Value = invFromDate;
dataWorksheet.Cells[6, 7].Value = invFromDate;
// Template specific excel generation goes in here
FillPurchaseExcelData(ref dataWorksheet, masterTable, subTable);
// save package
package.Save();
}
byte[] fileContent = newFile.ToArray();
#if DEBUG
string tempName = "MTemp.xlsx";
string tempFileName = System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]) + #"\" + tempName;
//Write the stream data of workbook to the root directory
using (FileStream file = new FileStream(tempFileName, FileMode.Create))
{
file.Write(fileContent, 0, fileContent.Length);
}
System.Diagnostics.Process.Start(tempFileName);
You can generate excel file and choose not to save it, but Excel can't open files that are not saved on disk (it becomes a 'file' when it's on disk), so in short - you have to save document in order to open it in Excel.
If you're concerned about storing data on hard drive, as an alternative you could create a data source on a medium you trust, and then create an xslx that would instruct Excel to consume that data source when opening worksheet (instead of creating a file pre-filled with data). But this is a whole other story...

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