Use DocumentFormat.Openxml 2.8.1.
I try to create Excel Sheet and create Table inside it. But when i do it - and try to open excel file - excel says that can not open and try to restore this file.
So, i create excel file:
var fStream = new FileStream(tempPathName, FileMode.Open, FileAccess.ReadWrite, FileShare.None, 1048, FileOptions.DeleteOnClose);
SpreadsheetDocument ssDoc = SpreadsheetDocument.Create(inputStream,
SpreadsheetDocumentType.Workbook);
Then , create sheet:
var tempPathName = Path.GetTempFileName();
WorkbookPart workbookPart = ssDoc.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
Sheets sheets = ssDoc.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());
WorksheetPart worksheetPart4 = workbookPart.AddNewPart<WorksheetPart>();
worksheetPart4.Worksheet = new Worksheet();
Worksheet workSheet4 = worksheetPart4.Worksheet;
var table = CreateTable1();
TableParts tableParts = new TableParts() { Count = (UInt32)1 };
TablePart tablePart = new TablePart() { Id = "rId" + 1 };
tableParts.Append(table);
tableParts.Append(tablePart);
workSheet4.AppendChild(tableParts);
Sheet sheet4 = new Sheet()
{
Id = ssDoc.WorkbookPart.GetIdOfPart(worksheetPart4),
SheetId = 4,
Name = "test"
};
sheets.Append(sheet4);
ssDoc.Close();
private Table CreateTable1()
{
// First, we create the table, its properties and we append it.
Table table = new Table();
TableProperties props = new TableProperties();
table.AppendChild<TableProperties>(props);
// Now we create a new layout and make it "fixed".
TableLayout tl = new TableLayout() { Type = TableLayoutValues.Fixed };
props.TableLayout = tl;
// Then we just create a new row and a few cells and we give them a width
var tr = new TableRow();
var tc1 = new TableCell();
var tc2 = new TableCell();
tc1.Append(new TableCellProperties(new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2000" }));
tc2.Append(new TableCellProperties(new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2000" }));
table.Append(tr);
return table;
}
So, how to create table in Excel sheet and insert data in table? Thank you.