I'm using EPPlus to write data to Excel, which works great. I'm writing a header row from column A to column AI and am using the code below to write the data
(subset of the code)
using (ExcelPackage pck = new ExcelPackage())
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add(customer);
ws.Cells["A1"].Value = "First Name";
ws.Cells["B1"].Value = "Last Name";
ws.Cells["C1"].Value = "Address1";
ws.Cells["D1"].Value = "Address2";
ws.Cells["E1"].Value = "City";
ws.Cells["F1"].Value = "State";
ws.Cells["G1"].Value = "Zip";
ws.Cells["H1"].Value = "Phone";
//keep writing data to I, J, K, L, etc
ws.Cells["AF1"].Value = "Hire Date";
ws.Cells["AG1"].Value = "Manager Name";
ws.Cells["AH1"].Value = "Manager Hire Date";
ws.Cells["AI1"].Value = "Simlcam Number";
FileInfo fi = new FileInfo("C:\\Test\\EPPlusWorkbook.xlsx");
await pck.SaveAsAsync(fi);
}
Now this code writes headers perfectly, UNTIL it reaches cell AF1 then for whatever reason the no further header info is written to the workbook.
Stepping thro the code shows that the lines of code are hit so there is no error displayed.
Related
I'm a student of Economic Sciences and i'm making a Program for my Final Paper about stock market. But, when i try to run my code in C# using EPPLUS, it doesn't working well. The STOCKHISTORY Formula isn't calculating and "#" is being inserted before the formula.
string Equity = "PETR4", FDate = "01/01/2019", LDate = "01/01/2022";
using (ExcelPackage Excel = new ExcelPackage(new FileInfo("Stock.xlsx")))
{
var Plan = Excel.Workbook.Worksheets.Add("Base");
Plan.Cells[1, 1].Value = FDate;
Plan.Cells[1, 2].Value = LDate;
Plan.Cells[1, 3].Value = Equity;
Plan.Cells[2, 1].Formula = $"STOCKHISTORY(C1, A1, B1)";
Excel.Workbook.Calculate();
Excel.Save();
Excel.Dispose();
}
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();
}
I am trying to create an Excel file using Open XML C#, where there are multiple sheets in my excel file that needs to be created. Please find my code below and help me with a solution.
When I open the excel only 1 sheet is present, sheet 2 is getting overwritten in sheet 1.
public void CreateExcelFile(string filePath , List<SheetData> excelSheet)
{
var sheetCount = GetSheetCount(filePath);
using (SpreadsheetDocument spreedDoc = SpreadsheetDocument.Create(filePath,
DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
{
Workbook workbook1 = new Workbook();
workbook1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
FileVersion fileVersion1 = new FileVersion() { ApplicationName = "xl", LastEdited = "5", LowestEdited = "4", BuildVersion = "9302" };
WorkbookProperties workbookProperties1 = new WorkbookProperties() { FilterPrivacy = true, DefaultThemeVersion = (UInt32Value)124226U };
BookViews bookViews1 = new BookViews();
WorkbookView workbookView1 = new WorkbookView() { XWindow = 240, YWindow = 105, WindowWidth = (UInt32Value)14805U, WindowHeight = (UInt32Value)8010U, ActiveTab = (UInt32Value)2U };
bookViews1.Append(workbookView1);
Sheets sheetCol = new Sheets();
int ctr = 0;
foreach (var sheetToCreate in excelSheet)
{
ctr++;
//WorksheetPart worksheetPart = null;
//worksheetPart = wbPart.AddNewPart<WorksheetPart>();
//var sheetData = new SheetData();
//worksheetPart.Worksheet = new Worksheet(sheetData);
//worksheetPart.Worksheet = new Worksheet(sheetToCreate);
string sheetName = "Sheet";
sheetName += ctr.ToString();
var sheet = new Sheet()
{
Id = "rId" + ctr,
SheetId = (UInt32)ctr,
Name = sheetName
};
sheet.Append(sheetToCreate);
sheetCol.Append(sheet);
//wbPart.Workbook.Sheets.AppendChild(sheet);
//wbPart.Workbook.Append(sheetCol);
workbook1.Sheets.Append(sheet);
//var workingSheet = ((WorksheetPart)wbPart.GetPartById(sheet.Id)).Worksheet;
}
workbook1.Append(fileVersion1);
workbook1.Append(workbookProperties1);
workbook1.Append(bookViews1);
workbook1.Append(sheetCol);
//Set Border
//wbPark
workbook1.Save();
}
}
When dealing with OpenXML, the "OpenXML Productivity Tool" (downloadable from Microsoft's site) is your friend. When I work with creating documents with OpenXML, I do the following:
Create a document similar to what I want using Excel or Word (in this case, an Excel spreadsheet document with two sheets (I labeled them "First" and "Second")).
Open the document up in the productivity tool
Reflect the code (a button on the Tool's UI)
Copy/paste the code I want.
If I do that, I end up with all the code I need. I've boiled it down to the essentials to answer your question. Excel will complain that the document produced below is corrupt (since all it includes is the code to create the two sheets - and leaves lots of other required code out - all of which is stealable from the tool). However, if you tell Excel "Repair this for me", you will get a document with two sheets, labeled "First" and "Second"
WorkbookPart workbookPart1 = document.AddWorkbookPart();
Workbook workbook1 = new Workbook() { MCAttributes = new MarkupCompatibilityAttributes() { Ignorable = "x15 xr xr6 xr10 xr2" } };
//lots of namespace declarations - copy them from the tool (they are needed!!)
//lots of code for WorkbookProperties, etc (you can get this from Tool)
Sheets sheets1 = new Sheets();
Sheet sheet1 = new Sheet() { Name = "First", SheetId = (UInt32Value)1U, Id = "rId1" };
Sheet sheet2 = new Sheet() { Name = "Second", SheetId = (UInt32Value)2U, Id = "rId2" };
sheets1.Append(sheet1);
sheets1.Append(sheet2);
//More elided code
workbook1.Append(sheets1);
workbookPart1.Workbook = workbook1;
I strongly recommend that you keep the pluralization of things like Sheet and Sheets clear. Your code has Sheets sheetCol = new Sheets();, it's not clear after that that sheetCol is a Sheets and not a Sheet.
Then you have something called sheetToCreate which is a SheetData object. Again, that's confusing - call it something clear like thisSheetData or something. I really strongly recommend that you follow the OpenXML naming as much as you can, otherwise it is extremely hard to follow what's going on.
The Productivity Tool is also handy once you've written out your file. You can see what you created, often spotting what the error is. In addition, there's a validate button that usually (not always) points you to problems in the structure of your documents.
Good luck. Prepare to get better at cussing at your code!
My worksheet is initially named in the 5th line of my code, but I want to rename it based off the workbook name in my case statement. It is not getting renamed. How to fix??
DateTime d = DateTime.Today;
string s = d.ToString("MMddyyyy");
using (ExcelPackage pck = new ExcelPackage())
{
ExcelWorksheet objWorksheet = pck.Workbook.Worksheets.Add("Sheet 1");
objWorksheet.Cells["A1"].LoadFromDataTable(dataTable, true);
switch (pageName)
{
case "abcd":
worksheetName = "abcd";
workbookName = "abcd_" + s + ".xlsx";
objWorksheet.Cells["A1:K20"].AutoFitColumns();
break;
}
}
Looks like you are modifying some unrelated local variable. You would need to modify the Name property on the sheet object:
objWorksheet.Name = "abcd";
Below is my code to read existing excel file:
FileInfo newFile = new FileInfo("C:\\Excel\\SampleStockTakeExceptionReport.xlsx");
using (ExcelPackage xlPackage = new ExcelPackage(newFile))
{
var ws = xlPackage.Workbook.Worksheets.Add("Content");
ws.View.ShowGridLines = false;
ws.Column(4).OutlineLevel = 1;
ws.Column(4).Collapsed = true;
ws.Column(5).OutlineLevel = 1;
ws.Column(5).Collapsed = true;
ws.OutLineSummaryRight = true;
//Headers
ws.Cells["B1"].Value = "Name";
ws.Cells["C1"].Value = "Size";
ws.Cells["D1"].Value = "Created";
ws.Cells["E1"].Value = "Last modified";
ws.Cells["B1:E1"].Style.Font.Bold = true;
System.Diagnostics.Process.Start("C:\\Excel\\SampleStockTakeExceptionReport.xlsx");
}
While I run the code. It throws a runtime error.
Error.
System.InvalidOperationException: A worksheet with this name already exists in the workbook
at OfficeOpenXml.ExcelWorksheets.Add(String Name)
at Report.Form1.ExportToExcel1(DataTable Tbl, String ExcelFilePath) in C:\SMARTAG_PROJECT\SUREREACH\EXCEL\Report\Report\Form1.cs:line 43
It's pretty straight forward, either:
first check if the worksheet exists and only if it doesn't then execute your code
just remove the existing worksheet if it exists and add it again with your values
modify those values for the existing worksheet "Content"
Try something like this maybe:
FileInfo newFile = new FileInfo("C:\\Excel\\SampleStockTakeExceptionReport.xlsx");
using (ExcelPackage xlPackage = new ExcelPackage(newFile))
{
//Check if worksheet with name "Content" exists and retrieve that instance or null if it doesn't exist
var ws = xlPackage.Workbook.Worksheets.FirstOrDefault(x => x.Name == "Content");
//If worksheet "Content" was not found, add it
if (ws == null)
{
ws = xlPackage.Workbook.Worksheets.Add("Content");
}
//Rest of code
}