ExcelPackage not Saving programmatically using C# - c#

I'm trying to edit an existing excel file with .xlsx extension using C#,but it is not saving the new value.My code is as follows.Can anybody help me?
string path = #"D:\Demo\test.xlsx" ;
FileInfo file = new FileInfo(Path.GetFileName(path));
using (ExcelPackage xlPackage = new ExcelPackage(file))
{
ExcelWorkbook workBook = xlPackage.Workbook;
ExcelWorksheet ws = workBook.Worksheets[1];
ws.Cells[8, 6].Value = 25;
xlPackage.Save();
}

Put the # symbol before your path string to prevent automatic stripping or manually escape your \ characters
string path = #"D:\test\test.xslx";
Or
string path = "D:\\test\\test.xslx";

Related

Insert into Existing excel file using EPP on C#

I want to insert value on my excel ,but i have a problem when i run my application, its create a new file excel ,doesnt insert value into existing file,
using (ExcelPackage excel = new ExcelPackage())
{
excel.Workbook.Worksheets.Add("Worksheet1");
// Target a worksheet
var worksheet = excel.Workbook.Worksheets["Worksheet1"];
worksheet.Cells[1, 1].Value = "Name";
worksheet.Cells[2, 1].Value = "ID";
FileInfo excelFile = new FileInfo(#"E:\ExcelTest.xls");
excel.SaveAs(excelFile);
I want my Program insert into existing file ,not create a new one,
how i can solve this?
The EPPlus Wiki Getting Started covered this exact scenario.
FileInfo excelFile = new FileInfo(#"E:\ExcelTest.xls");
using (ExcelPackage excel = new ExcelPackage(excelFile))
{
// Target a worksheet
var worksheet = excel.Workbook.Worksheets["Worksheet1"];
worksheet.Cells[1, 1].Value = "Name";
worksheet.Cells[2, 1].Value = "ID";
excel.Save();
}

EPPlus:Cannot access a closed Stream when copy existing excel worksheet

I'm currently using EPPlus and right now I'm trying to copy existing worksheet from an excel file and add the copied worksheet to another excel file. But then, Ive encounter this error:
Full Stack Trace
System.ObjectDisposedException: Cannot access a closed Stream.
at System.IO.MemoryStream.Seek(Int64 offset, SeekOrigin loc)
at OfficeOpenXml.Packaging.ZipPackagePart.GetStream(FileMode fileMode, FileAccess fileAccess)
at OfficeOpenXml.Packaging.ZipPackagePart.WriteZip(ZipOutputStream os)
at OfficeOpenXml.Packaging.ZipPackage.Save(Stream stream)
at OfficeOpenXml.ExcelPackage.Save()
at OfficeOpenXml.ExcelPackage.SaveAs(Stream OutputStream)
Excel Helper
public byte[] ExportStraightBoxClampPreview(PreviewInputDto input)
{
//the path of the file
string filePath = #"C:\Preview\WeldedStraightBox.xlsx";
string filePath1 = #"C:\Preview\Strongback.xlsx";
//create a fileinfo object of an excel file on the disk
FileInfo file = new FileInfo(filePath);
FileInfo file1 = new FileInfo(filePath1);
FileInfo file2 = new FileInfo(filePath2);
//create a new Excel package from the file
using (ExcelPackage strongBack = new ExcelPackage(file1))
using (ExcelPackage excelPackage = new ExcelPackage(file))
{
ExcelWorksheet wsSrc = strongBack.Workbook.Worksheets.First();
ExcelWorksheet wsDest = excelPackage.Workbook.Worksheets[wsSrc.Name] ?? excelPackage.Workbook.Worksheets.Add(wsSrc.Name, wsSrc);
** error here **------> return excelPackage.GetAsByteArray();
}
Is it because I do not use Memory Stream? But then If I manually copied using looping for each row and column, it is working:
another method
ExcelWorksheet wsSrc = strongBack.Workbook.Worksheets.First();
ExcelWorksheet wsDest = excelPackage.Workbook.Worksheets[wsSrc.Name] ?? excelPackage.Workbook.Worksheets.Add(wsSrc.Name);
for (var r = 1; r <= wsSrc.Dimension.Rows; r++)
{
for (var c = 1; c <= wsSrc.Dimension.Columns; c++)
{
var cellSrc = wsSrc.Cells[r, c];
var cellDest = wsDest.Cells[r, c];
// Copy value
cellDest.Value = cellSrc.Value;
// Copy cell properties
cellDest.Style.Numberformat = cellSrc.Style.Numberformat;
cellDest.Style.Font.Bold = cellSrc.Style.Font.Bold;
// TODO... Add any additional properties that you may want to copy over
}
}
I'm really sorry for the lack of knowledge about this. I'm really appreciate any help.

VSTO Excel Read from Current Open Workbook

Is it possible to read from an open Excel (xlsx) using EPPlus? I want the user to be able to open an Excel document, click the Add-In button and read data from the active worksheet. I don't need to write to the worksheet, only read from it.
Using interop I was able to get the full path to the open workbook but when I tried to actually access the workbook I got an I/O error. Any ideas how to get around this?
var test = ( Microsoft.Office.Interop.Excel.Workbook ) Globals.ThisAddIn.Application.ActiveWorkbook;
var test2 = test.ActiveSheet;
//var test21 = ( Microsoft.Office.Interop.Excel.Workbook ) Globals.ThisAddIn.Application.ActiveSheet;
var test3 = new FileInfo( test.FullName );
using ( ExcelPackage package = new ExcelPackage( test3) ) // <--- I/O error here
{
var worksheet = package.Workbook.Worksheets[ "Sheet1" ];
string myString = String.Format( "{0}", worksheet.Cells[ 1, 1 ].Text );
}
Try non-exclusive access, like this:
....
var stream = new FileStream(test.FullName, FileMode.Open, FileAccess.Read,
FileShare.ReadWrite); // <<< ---!!
using (ExcelPackage package = new ExcelPackage(stream))
{
...
}

Convert XLSX to PDF on one page by Spire.Pdf (c#)

I have one page XLSX work sheet (invoice). I need to convert it to one page PDF document. For it I am using Spire library. But it covert my document to two pages.
Code:
using (ExcelPackage xlPackageRef = new ExcelPackage(totalXlsFile))
{
using (ExcelPackage xlPackage = new ExcelPackage(workXlsFile))
{
ExcelWorkbook wb = xlPackage.Workbook;
ExcelWorkbook wbRef = xlPackageRef.Workbook;
var sheetName = invoice.XlsSeznamFakturNazevListu;
OfficeOpenXml.ExcelWorksheet wsRef = wbRef.Worksheets[sheetName];
if (wsRef != null)
{
// create xls work file
wb.Worksheets.Add("faktura", wsRef);
xlPackage.Save();
// load Excel file
Workbook workbook = new Workbook();
workbook.LoadFromFile(workXlsFilePath);
// pdf file path
FileInfo pdfInvoiceFile = new FileInfo(pdfInvoiceTargetFolder + #"/" + pdfInvoiceFileName);
if (pdfInvoiceFile.Exists)
pdfInvoiceFile.Delete();
// create pdf file
workbook.SaveToFile(pdfInvoiceFile.FullName, Spire.Xls.FileFormat.PDF);
}
}
}
First, I suppose you were using Spire.XLS rather than Spire.PDF.
Second, you need to do some page setup before converting. Try below code:
Worksheet worksheet = workbook.Worksheets[index];
PageSetup setup = worksheet.PageSetup;
setup.FitToPagesWide = 1;
setup.FitToPagesTall = 1;

opening .xlsx in office 2003

I have created a .xlsx using openxml.
I am not able to open this file in office 2003.. I have also tried using compatibility pack but still the file does not open. What can be done if i need to generate .xlsx that can be opened in office 2003 as well.
Code i am using to generate .xlsx is :
public static void HelloWorldXlsx(string docName)
{
SpreadsheetDocument package = SpreadsheetDocument.Create(docName, SpreadsheetDocumentType.Workbook);
package.AddWorkbookPart();
package.WorkbookPart.Workbook = new Workbook();
WorksheetPart wspart = package.WorkbookPart.AddNewPart<WorksheetPart>();
Cell cell = new Cell();
cell.DataType = CellValues.InlineString;
cell.InlineString = new InlineString(new DocumentFormat.OpenXml.Spreadsheet.Text("Hello World!"));
wspart.Worksheet = new Worksheet(new SheetData(new Row(cell)));
wspart.Worksheet.Save();
package.WorkbookPart.Workbook.AppendChild(new Sheets());
Sheet sheet = new Sheet();
sheet.Id = package.WorkbookPart.GetIdOfPart(wspart);
sheet.SheetId = 1;
sheet.Name = "Hello !";
package.WorkbookPart.Workbook.GetFirstChild<Sheets>().AppendChild<Sheet>(sheet);
package.WorkbookPart.Workbook.Save();
package.Close();
}
Thanks for suggestion. I got the answer to my question .. I had not set cellReference property of Cell in my code.

Categories