I'm using Documentformat.Openxml package
[https://learn.microsoft.com/en-us/dotnet/api/documentformat.openxml.spreadsheet?view=openxml-2.8.1]
to generate a Pivot table in a CSV dynamically from a Dictionary<string, List<string>> object which has a structure similar to this:
I'm following the Sample here to create the table which should look somewhat like:
but not sure about how to create the table from the dictionary of data.
My current code snippet:
// Add a WorkbookPart to the document.
WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
// Add a WorksheetPart to the WorkbookPart.
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
// Add Sheets to the Workbook.
Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild(new Sheets());
// Append a new worksheet and associate it with the workbook.
Sheet sheet = new Sheet()
{
Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "mySheet"
};
sheets.Append(sheet);
Worksheet worksheet = new Worksheet();
SheetData sheetData = new SheetData();
Row row = new Row();
Cell cell = new Cell()
{
CellReference = "A1",
DataType = CellValues.String,
CellValue = new CellValue("Microsoft")
};
row.Append(cell);
sheetData.Append(row);
worksheet.Append(sheetData);
worksheetPart.Worksheet = worksheet;
// Close the document.
spreadsheetDocument.Close();
In the above snippet, you can see that I'm hardcoding the cell value but in reality I want to populate it dynamically from the dictionary and there is a large amount of data in it. What is the best way to do this? Can someone please help?
As your question shows you want to generate excel file using Open XML. You should take a look at these answers
1 Using open XML to create excel file
2 How do you convert Excel to CSV using OpenXML SDK?
and for other websites you can visit
3 https://www.c-sharpcorner.com/article/export-and-import-excel-file-using-closedxml-in-asp-net-mvc/
Related
I want to display number 3123.45 as 3,123.45 by using C# as follow coding. I tried many codes but didn't find good example and code.
public static void CreateSpreadsheetWorkbook(string filepath)
{
// Create a spreadsheet document by supplying the filepath.
// By default, AutoSave = true, Editable = true, and Type = xlsx.
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(filepath, SpreadsheetDocumentType.Workbook);
// Add a WorkbookPart to the document.
WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
// Add a WorksheetPart to the WorkbookPart.
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
// Add Sheets to the Workbook.
Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());
// Append a new worksheet and associate it with the workbook.
Sheet sheet = new Sheet() { Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "mySheet" };
sheets.Append(sheet);
workbookpart.Workbook.Save();
// Close the document.
spreadsheetDocument.Close();
}
You need to set the style for the selected column that you want:
sheet.Column(columnIndex).Style.Numberformat.Format = "#,##0.00";
I think you can also do this for cells.
Please consider this Excel:
and it's XML:
I want to create such this Excel that has multiple merged cells using OpenXML.
How I can do this?
thanks
You can use the MergeCells and MergeCell classes to create the merged cells you require. The MergeCells class is the collection of merge cells (<mergeCells count="3"> in your XML) and the MergeCell class represents each individual set of merged cells (<mergeCell ref="xx:xx" /> in your XML). To populate data in the merged cells you need to add the value to the upper left most cell; any other values will be ignored.
The following code will create a new file with merged cells.
using (SpreadsheetDocument myDoc = SpreadsheetDocument.Create(filename, SpreadsheetDocumentType.Workbook))
{
WorkbookPart workbookpart = myDoc.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
// Add a WorksheetPart to the WorkbookPart.
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
SheetData sheetData = new SheetData();
//add a row
Row firstRow = new Row();
firstRow.RowIndex = (UInt32)1;
//create a cell in C1 (the upper left most cell of the merged cells)
Cell dataCell = new Cell();
dataCell.CellReference = "C1";
CellValue cellValue = new CellValue();
cellValue.Text = "99999";
dataCell.Append(cellValue);
firstRow.AppendChild(dataCell);
sheetData.AppendChild(firstRow);
// Add a WorkbookPart to the document.
worksheetPart.Worksheet = new Worksheet(sheetData);
//create a MergeCells class to hold each MergeCell
MergeCells mergeCells = new MergeCells();
//append a MergeCell to the mergeCells for each set of merged cells
mergeCells.Append(new MergeCell() { Reference = new StringValue("C1:F1") });
mergeCells.Append(new MergeCell() { Reference = new StringValue("A3:B3") });
mergeCells.Append(new MergeCell() { Reference = new StringValue("G5:K5") });
worksheetPart.Worksheet.InsertAfter(mergeCells, worksheetPart.Worksheet.Elements<SheetData>().First());
//this is the part that was missing from your code
Sheets sheets = myDoc.WorkbookPart.Workbook.AppendChild(new Sheets());
sheets.AppendChild(new Sheet()
{
Id = myDoc.WorkbookPart.GetIdOfPart(myDoc.WorkbookPart.WorksheetParts.First()),
SheetId = 1,
Name = "Sheet1"
});
}
The code above produces:
I have an .xlsx file, which already has some data.
I want to enter some data on I1 cell.
Update:
I tried this:
WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
SheetData sheetData = worksheetPart.Worksheet.Elements<SheetData>().First();
Row row1 = new Row()
{
RowIndex = (UInt32Value)1U
};
Cell cell = new Cell() { CellReference = "I1" };
CellFormula cellformula = new CellFormula();
cellformula.Text = "IF(A2 = A1,1,0)";
CellValue cellValue = new CellValue();
cellValue.Text = "0";
cell.Append(cellformula);
cell.Append(cellValue);
row1.Append(cell);
sheetData.Append(row1);
But it is not working.
Please provide sample code with your answer.
You are creating a new Row object even though one already exists in your document. You then give it a RowIndex which also already exists which means you'll end up with a corrupted file (you can't have two rows with the same index).
You need to find the existing Row and add your new Cell to that rather than creating a brand new Row. The easiest way to do that is to call GetFirstChild<Row> on sheetData.
As an aside, I would also not write the CellValue to the Cell as you are using a formula. In that instance the Value is used by Excel to prevent it having to recalculate the formula when the sheet loads. In your example though your value is wrong. Omitting the value altogether is probably the easiest way to guarentee correctness as Excel will then calculate the formula when the sheet loads.
That leads to the following code:
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(filename, true))
{
WorkbookPart workBookPart = spreadsheetDocument.WorkbookPart;
WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
SheetData sheetData = worksheetPart.Worksheet.Elements<SheetData>().First();
//find the first row in the sheet data
Row row1 = sheetData.GetFirstChild<Row>();
//create a new cell
Cell cell = new Cell() { CellReference = "I1" };
CellFormula cellformula = new CellFormula();
cellformula.Text = "IF(A2 = A1,1,0)";
cell.Append(cellformula);
//append the cell to the row
row1.Append(cell);
}
I've been struggeling with creating worksheets for my xlsx file. Adding the first worksheet isn't a problem, but when I want a second sheet, the exported xlsx seems to be corrupt. Who can point out to me what I'm doing wrong?
Note: I already tried to also call 'workbookpart,Workbook.Save();' right after creating the first Workbook, but without the required result.
protected void export_Click(object sender, EventArgs e)
{
ExportToExcel(#"D:\dev\Dotnet4\Excel\test.xlsx");
}
private void ExportToExcel(string filepath)
{
SpreadsheetDocument spreadsheetDocument;
WorkbookPart workbookpart;
CreateSpreadsheet(filepath, out spreadsheetDocument, out workbookpart);
CreateWorksheet(spreadsheetDocument, workbookpart, "My sheet 1");
CreateWorksheet(spreadsheetDocument, workbookpart, "My sheet 2");
workbookpart.Workbook.Save();
// Close the document.
spreadsheetDocument.Close();
}
private static void CreateWorksheet(SpreadsheetDocument spreadsheetDocument, WorkbookPart workbookpart, string worksheetName)
{
// Add a WorksheetPart to the WorkbookPart.
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
// Add Sheets to the Workbook.
Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.
AppendChild<Sheets>(new Sheets());
// Append a new worksheet and associate it with the workbook.
Sheet sheet = new Sheet()
{
Id = spreadsheetDocument.WorkbookPart.
GetIdOfPart(worksheetPart),
SheetId = 1,
Name = worksheetName
};
sheets.Append(sheet);
}
private static void CreateSpreadsheet(string filepath, out SpreadsheetDocument spreadsheetDocument, out WorkbookPart workbookpart)
{
// Create a spreadsheet document by supplying the filepath.
// By default, AutoSave = true, Editable = true, and Type = xlsx.
spreadsheetDocument = SpreadsheetDocument.
Create(filepath, SpreadsheetDocumentType.Workbook);
// Add a WorkbookPart to the document.
workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
}
I think you have 2 small issues:
The SheetId is the same for both sheets you are adding which is invalid.
You are adding a new Sheets element each time you call CreateWorksheet but there should only be one such element in the XML (there are many Sheet's but not many Sheets!).
To solve 1 you could use the count of the sheets.ChildElements. As this is 0 first time round and one the second you'll need to add 1 to it. If you prefer you could take it in to CreateWorksheet as a parameter; it doesn't really matter as long as they start at 1 and are different.
To solve 2 you can perform a null check on the Sheets property of the Workbook and only create it if it doesn't already exist.
The below should do what you're after.
private static void CreateWorksheet(SpreadsheetDocument spreadsheetDocument, WorkbookPart workbookpart, string worksheetName)
{
// Add a WorksheetPart to the WorkbookPart.
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
// Add Sheets to the Workbook.
if (spreadsheetDocument.WorkbookPart.Workbook.Sheets == null)
{
//spreadsheetDocument.WorkbookPart.Workbook.Sheets = new Sheets();
spreadsheetDocument.WorkbookPart.Workbook
.AppendChild<Sheets>(new Sheets());
}
Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.Sheets;
// Append a new worksheet and associate it with the workbook.
Sheet sheet = new Sheet()
{
Id = spreadsheetDocument.WorkbookPart.
GetIdOfPart(worksheetPart),
SheetId = (UInt32)sheets.ChildElements.Count + 1,
Name = worksheetName
};
sheets.Append(sheet);
}
One final point is that SpreadsheetDocument implements IDisposable so it should be disposed after use.
I've been using OPEN XML to create a spread sheet which can then be downloaded. I want to set the column widths and also change the header to bold. I've done this using Office.Interop.Excel but I'm struggling with this format. My code is below, you can see I've set up a font but have been unable to assign it to my spread sheet, I have got messages saying it's not possible to assign to a tree.
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(fileName, SpreadsheetDocumentType.Workbook); //Open(fileName, true);
try
{
WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet(new SheetData());
DocumentFormat.OpenXml.Spreadsheet.Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild<DocumentFormat.OpenXml.Spreadsheet.Sheets>(new DocumentFormat.OpenXml.Spreadsheet.Sheets());
Sheet sheet = new Sheet() { Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Models" };
sheets.Append(sheet);
DocumentFormat.OpenXml.Spreadsheet.Font boldFont = new DocumentFormat.OpenXml.Spreadsheet.Font();
Bold bFontBold = new Bold();
boldFont.Append(bFontBold);
DocumentFormat.OpenXml.Spreadsheet.Worksheet worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet();
SheetData sheetData = new SheetData();
........
Row row = new Row();
Cell cell = new Cell()
{
CellReference = "A" + (intI + 1),
DataType = CellValues.String,
CellValue = new CellValue(ModelBookrowDetail[0])
};
row.Append(cell);
Cell cell2 = new Cell()
{
CellReference = "B" + (intI + 1),
DataType = CellValues.String,
CellValue = new CellValue(ModelBookrowDetail[1])
};
row.Append(cell2);
.........
sheetData.Append(row);
}
worksheet.Append(sheetData);
worksheetPart.Worksheet = worksheet;
spreadsheetDocument.Close();
}
catch
{
spreadsheetDocument.Close();
}
I don't know how set you are on using OpenXml. I might suggest looking into ClosedXml. Up until now it has saved me a lot of manhours. It only has one downside to it, and that is that it doesn't manage Word documents like OpenXml does.
ClosedXml is a more object oriented Open Source Library, and is far more well documented in contrast to what i have experienced with OpenXml.
You can find ClosedXml here:
https://github.com/ClosedXML/ClosedXML
Best of luck
Olliver