Copy sheet from one workbook to another using NPOI in C# - 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.

Related

Get Active or Default Sheet using ExcelDataReader

How can I get content of the Active sheet or the default sheet of an .xlsx workbook? I have to read many workbooks and I do not know the name of the Active sheets.
FileStream stream = File.Open("C:\\test\\test.xlsx", FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
excelReader.IsFirstRowAsColumnNames = true;
while (excelReader.Read()) {
Console.WriteLine(excelReader.GetString(0));
}
I know how to do it using OfficeOpenXml but ExcelDataReader is lightweight and AsDataSet makes it very easy to turn excel data into JSON.
Using (var pck = new OfficeOpenXml.ExcelPackage()) {
using (var stream = System.IO.File.OpenRead(path))
{
pck.Load(stream);
}
var ws = pck.Workbook.Worksheets.FirstOrDefault(f => f.View.TabSelected);
string ActiveSheetName = ws.Name;
}
Any help here is highly appreciated!

Can not read from inputstream in FileMode.Append,FileAccess.Write

I am trying to read a excel file using
using (var stream = new FileStream(filepath, FileMode.Append,FileAccess.Write))
{
ExcelWorksheet worksheet;
using (ExcelPackage pck = new ExcelPackage(stream))
actually I am trying to add a worksheet in existing excel file so that's why I am using append , and when I used filemode.create then it is overtiring my existing tab with the new one so what should I do?
Just use the following code and it will add a new worksheet to your current file:
FileInfo newFile = new FileInfo("YourFile.xlsx");
using (ExcelPackage p = new ExcelPackage(newFile))
{
p.Workbook.Worksheets.Add("YourNewSheet");
p.Save();
}
You can do the same actions easily with Microsoft open xml
https://learn.microsoft.com/en-us/office/open-xml/how-to-get-worksheet-information-from-a-package

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

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 large XLSX files

I have an application that have to read excel and convert it to array. So far so good. Everything works file until I try to convert a larger file. I try OpenXML and try SAX approach:
using (SpreadsheetDocument xlsx = SpreadsheetDocument.Open(filePath, false))
{
WorkbookPart workbookPart = xlsx.WorkbookPart;
List<List<string>> parsedContent = new List<List<string>>();
foreach (WorksheetPart worksheet in workbookPart.WorksheetParts)
{
OpenXmlReader xlsxReader = OpenXmlReader.Create(worksheet);
while (xlsxReader.Read())
{
}
}
}
This is working well for files in range 1 - 10MB. My problem is when I try to load 10+ MB file. The result is OutOfMemoryException. How to proper read that big chunk of data? How to do it memory efficient?
P.s. I try libraries like ClosedXML, EPPlus and few others.
Every solution will be appreciated. Thank you in advance
If you plan on only performing a read on the excel file content, I suggest you use the ExcelDataReader library instead Link, which extracts the worksheetData into a DataSet object.
IExcelDataReader reader = null;
string FilePath = "PathToExcelFile";
//Load file into a stream
FileStream stream = File.Open(FilePath, FileMode.Open, FileAccess.Read);
//Must check file extension to adjust the reader to the excel file type
if (Path.GetExtension(FilePath).Equals(".xls"))
reader = ExcelReaderFactory.CreateBinaryReader(stream);
else if (Path.GetExtension(FilePath).Equals(".xlsx"))
reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
if (reader != null)
{
//Fill DataSet
DataSet content = reader.AsDataSet();
//Read....
}
Use ExcelDataReader. It is easy to install through Nuget and should only require a few lines of code:
Nuget:
Install-Package ExcelDataReader
Usage:
using (FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
{
using (IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream))
{
DataSet result = excelReader.AsDataSet();
foreach (DataRow dr in result[0])
{
//Do stuff
}
}
}

Categories