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))
{
...
}
Related
I am struggling for creating and saving a pivot table, I ran the code below with no error, but failed to open the excel file.
Here is my code:
public void Execute()
{
IWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet("sample");
IRow row0 = sheet.CreateRow(0);
row0.CreateCell(0).SetCellValue("test");
row0.CreateCell(1).SetCellValue("a");
row0.CreateCell(2).SetCellValue("b");
IRow row1 = sheet.CreateRow(1);
row1.CreateCell(0).SetCellValue("asd");
row1.CreateCell(1).SetCellValue("das");
row1.CreateCell(2).SetCellValue("fgh");
var tl = row0.GetCell(0);
var br = row1.GetCell(2);
CellReference topLeft = new CellReference(tl);
CellReference botRight = new CellReference(br);
AreaReference aref = new AreaReference(topLeft, botRight);
CellReference pos = new CellReference(3, 3);
XSSFPivotTable pivotTable = sheet.CreatePivotTable(aref, pos);
using (FileStream fileWritter = new FileStream("test.xlsx", FileMode.Create, FileAccess.Write))
{
workbook.Write(fileWritter);
}
}
The error of opening the file:
Removed Part: /xl/pivotCache/pivotCacheDefinition1.xml part with XML error. (PivotTable cache) HRESULT 0x8000ffff Line 1, column 0. Removed Part: /xl/pivotTables/pivotTable1.xml part with XML error. (PivotTable view) HRESULT 0x8000ffff Line 1, column 0.
Please help!
I found the answer on my own: using Microsoft.Office.Interop.Excel to do boring steps in Excel.
I used macro recorder in Excel to generate source code, and then just easily edited the code in any language that I want.
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.
I have a project VSTO EXCEL. I would like to work with ClosedXML library, but can`t get the link on the open ActiveSheet. My code:
private void ThisWorkbook_Startup(object sender, System.EventArgs e)
{
var workbook = **?**;
var ws = workbook.Worksheet(1);
var rngHeaders = ws.Range("B3:F3");
rngHeaders.Style.Fill.BackgroundColor = XLColor.LightSalmon;
}
This example does`t work:
var workbook = ThisApplication.ThisWorkbook;
I know there is this way:
using (var workbook = new XLWorkbook())
{
var worksheet = workbook.Worksheets.Add("Sample Sheet");
worksheet.Cell("A1").Value = "Hello World!";
workbook.SaveAs("HelloWorld.xlsx");
}
But I have to work with already opened Workbook.
To open an Excel file with ClosedXML, you have to open a saved file (by filename) or a filestream. You can't open a workbook which is already opened in Excel or another application.
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;
I always get an exception when writing to newly created file. I get this exception even if provided sheet is empty. Workbook without sheets saves without a problem.
This exception shows for an empty sheet.
Additional information: calculated end index (1932) is out of
allowable range (1908..1910)
I'm using NOPI.dll ver.2.1.3.1 http://npoi.codeplex.com/
File I try to create is .xls (Excel 97-2003)
filePath in code bolow has a value #"C:\TB\Report.xls"
My code
public void Generate()
{
HSSFWorkbook newWorkBook = new HSSFWorkbook();
ISheet newSheet = newWorkBook.CreateSheet("Main");
newWorkBook.Add(newSheet);
using (FileStream fileOut = new FileStream(filePath, FileMode.Create))
{
newWorkBook.Write(fileOut);
}
}
File is created but it's empty.
When creating xls with sheet that has rows and columns the result is the same except the numbers in exception are higher.
The problem was using ISheet instead of HSSFSheet. Example shown in the documentation used ISheet but it was incorrect.
Correct code:
public void Generate()
{
HSSFWorkbook newWorkBook = new HSSFWorkbook();
HSSFSheet newSheet = (HSSFSheet)newWorkBook.CreateSheet("Main");
var headerRow = newSheet.CreateRow(0);
var headerCell = headerRow.CreateCell(0);
headerCell.SetCellValue("Something");
using (FileStream fileOut = new FileStream(filePath, FileMode.Create))
{
newWorkBook.Write(fileOut);
}
}