Unable to delete a worksheet using EPPlus - c#

I am using this code:
ExcelPackage pck = new ExcelPackage(newFile);
var wk = pck.Workbook.Worksheets.SingleOrDefault(x => x.Name == "Content");
pck.Workbook.Worksheets.Delete(wk);
But in delete it gives me "IndexOutOfRangeException", but I am trying to delete from object, I have tried to delete by index "1", I just have two worksheets, and the same exception. The file and worksheet is not null, but when I execute delete in anyway I receive the "IndexOutOfRangeException".
What's happening?
Note: I have created this worksheet from ExcelPackage too and now i want delete it.

Looks like you ran into some temporary bug/issue, that was already fixed. As of EpPlus 4.0.1.1, the following code works just fine:
var workbookFileInfo = new FileInfo(#"Workbook.xlsx");
using (var excelPackage = new ExcelPackage(workbookFileInfo))
{
excelPackage.Workbook.Worksheets.Add("Worksheet1");
excelPackage.Workbook.Worksheets.Add("Worksheet2");
excelPackage.Save();
}
using (var excelPackage = new ExcelPackage(workbookFileInfo))
{
var worksheet = excelPackage.Workbook.Worksheets.SingleOrDefault(x => x.Name == "Worksheet1");
excelPackage.Workbook.Worksheets.Delete(worksheet);
excelPackage.Save();
}
Try to update to the latest available stable version of EpPlus and if will not help you, please post additional details applicable for the latest version.

Related

SSIS: Script task to delete specific rows in Excel

I am using a script task to delete particular rows in an Excel in SSIS. Previously it was working fine, then when I try to implement everything again I am getting error in the .Delete() codes. Find my code below,
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
var dir = new System.IO.DirectoryInfo(#"D:\Data_Processing\Input");
var fullFilePath = dir.GetFiles("*.xlsx").Select(f => f.FullName).FirstOrDefault();
if (fullFilePath != null)
{
Microsoft.Office.Interop.Excel.Workbook workBook = excelApp.Workbooks.Open(fullFilePath);
foreach (Worksheet sheet in workBook.Worksheets)
{
sheet.Rows[8].Delete();
sheet.Rows[7].Delete();
sheet.Rows[6].Delete();
sheet.Rows[5].Delete();
sheet.Rows[4].Delete();
sheet.Rows[3].Delete();
sheet.Rows[2].Delete();
sheet.Rows[1].Delete();
}
workBook.Save();
workBook.Close(false);
excelApp.Application.Quit();
System.IO.File.Move(fullFilePath, #"D:\HC_Report.xlsx");
Dts.Variables["User::FileExistsFlg"].Value = 1;
}
else
{
Dts.Variables["User::FileExistsFlg"].Value = 0;
}
Dts.TaskResult = (int)ScriptResults.Success;
And when I try to add Microsoft.Office.Interop.Excel in the References it is coming with a different icon as below
Can anyone please help with this ?
Thanks,
I have manually added the .dll file from this location C:\WINDOWS\assembly\GAC_MSIL\Microsoft.Office.Interop.Excel\15.0.0.0__71e9bce111e9429c\Microsoft.Office.Interop.Excel.dll and then the error disappeared.

EPPlus producing an empty Excel file after SaveAs

I'm using the latest 4.5.3.3 nuget version. .NET 4.6.1.
No issues if I create an excel file from scratch, but if I need to update an existing one, even if passing it to the ExcelPackage ctor and calling a ExcelPackage.Save after updating the data, or create a copy of the original excel file to pass to ExcelPackage ctor I obtain the same result.
FileInfo exc = new FileInfo(destPath);
using (var ep = new ExcelPackage(exc))
{
foreach (var sheet in _resultTranslations.Keys)
{
List<string> sheetTrs = _resultTranslations[sheet];
var ws = ep.Workbook.Worksheets[sheet];
if (ws == null)
continue;
for (int r = 0; r < sheetTrs.Count; r++)
{
ws.Cells[2 + r, 6].Value = sheetTrs[r];
}
}
ep.Save();
}
UPDATE:
If I open the Excel file with Office 2016, and save it without any changes, EEPlus updates it correctly (it's no more blank).
Any suggestion?
Thanks.

How to create an xls file with NPOI?

All I want to do is to create a file with 1 line and few columns to make some test.
However I cannot find a simple way to do such a thing. Most help I found seem to also use a database.
I found one that doesn't.
Trying to create a new .xlsx file using NPOI and write to it
However it seems like a little too much for such a simple task. Is there a tool which would allow me to do something as simple as
Create file
file.cell[0,0] = ...
You could use the EPPlus package. Find it on NuGet.
string fileName = #"C:\test\MyNewExcelFile.xlsx";
FileInfo newFile = new FileInfo(fileName);
using (ExcelPackage xlPackage = new ExcelPackage(newFile)) // create the xlsx file
{
// Add a new worksheet on which to put data
ExcelWorksheet xlWorksheet = xlPackage.Workbook.Worksheets.Add("Test");
// Write data to cell(s)
xlWorksheet.Cells["A1"] = ...
// Write the file
xlPackage.Save();
}
EDIT
Modification to replace worksheet if it already exists.
const string fileName = #"C:\test\MyNewExcelFile.xlsx";
const string sheetName = #"test";
FileInfo newFile = new FileInfo(fileName);
using (ExcelPackage xlPackage = new ExcelPackage(newFile)) // create the xlsx file
{
// if sheet already exists, delete it
// use LINQ to query collection of worksheets
ExcelWorksheet xlWorksheet = xlPackage.Workbook.Worksheets.SingleOrDefault(ws => ws.Name == sheetName);
if (xlWorksheet != null)
{
// worksheet exists - delete it
xlPackage.Workbook.Worksheets.Delete(sheetName);
}
// Add new worksheet on which to put data
ExcelWorksheet xlWorksheet = xlPackage.Workbook.Worksheets.Add("Test");
// Write data to cell(s)
xlWorksheet.Cells["A1"] = ...
// Write the file
xlPackage.Save();
}

How to add a new sheet to an exising Excel file with EPPlus?

Using EPPlus I want to add a new sheet to an Excel file but I do not want to delete the existing sheets in the file if any, and I want to insert it as the first sheet in the file.
Here is what I have written for a quick test but it deletes all the existing sheets:
using (ExcelPackage p = new ExcelPackage())
{
p.Workbook.Worksheets.Add("HubaHuba");
p.Workbook.Worksheets.MoveToStart("HubaHuba");
ExcelWorksheet ws = p.Workbook.Worksheets[1];
ws.Name = "HubaHuba";
var cell = ws.Cells[1, 1];
cell.Value = "dfsdfsdfsd";
cell = ws.Cells[1, 2];
cell.Value = "347895y5 Oh";
Byte[] bin = p.GetAsByteArray();
File.WriteAllBytes(path,bin);
}
using (ExcelPackage excelEngine = new ExcelPackage())
{
excelEngine.Workbook.Worksheets.Add("sheet1");
excelEngine.Workbook.Worksheets.Add("sheet2");
excelEngine.Workbook.Worksheets.Add("sheet3");
String myFile= "c:\....\xx.xlsx";
excelEngine.SaveAs();
}
When you use Add the sheet is added at the and of current file sheets.
If you want to add in a specific position use this function:
excelEngine.Workbook.Worksheets.Add("sheet0");
excelEngine.Workbook.Worksheets.MoveBefore(4, 1);
sheet0 is added at the and in 4th position and you move it in first position with the previous code.
That's because you're rewriting the file with command File.WriteAllBytes. Instead you should just call p.Save() and ExcelPackage needs to use the constructor that accepts the file path. Then it will work.

Using ExcelPackage to Read from Excel Template and Write to Excel

I am using the following bit of code:
var assembly = Assembly.GetExecutingAssembly();
Stream streamToTemplete=assembly.GetManifestResourceStream("DailyAuction.xltx");
Stream streamToOutput = assembly.GetManifestResourceStream("dailyAuctionEmail.xls");
//using (ExcelPackage excelPackage = new ExcelPackage(newFile, templateFile))
using(streamToTemplete)
using (streamToOutput)
{
using (ExcelPackage excelPackage = new ExcelPackage(streamToOutput, streamToTemplete))
{
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets["Daily Auction"];
int startRow = 4;
int row = startRow;
foreach (DailyEmail dailyEmail in listDailyEmail) //iterate through all the rows in the list
{
worksheet.Cells[row, 1].Value = dailyEmail.As_At.ToString("dd-MMM-yy HH:mm");
worksheet.Cells[row, 2].Value = dailyEmail.Auction_Date.ToString("dd-MMM-yy");
}
excelPackage.Save();
}
}
var attachment = new Attachment(streamToOutput, new ContentType("application/vnd.ms-excel"));
However, I am getting an error saying streamToTemplate & streamToOutput are null. What seems to be the problem? Also, will the rest of the code work?
Check the properties on both the Excel files. Build Action should be 'Embedded Resource'.
Also, the string that you are providing to GetManifestResource stream looks too simple. The string should be:
<defaultNamespace>.<folderName>.<fileName> MSDN Article
This answer suggests calling the GetManifestResourceNames, then using the debugger to take a look at the resource names. Seems a good way to go while you're finding your way.

Categories

Resources