我有以下代码,它没有将值保存到单元格和文件中。它在字段中显示值,cell.cellvalue
但没有将其写入 excel。我不知道如何保存文件。我使用了 OpenXml-SDK,并将datatable
值写入每个cell/row
创建的电子表格文档。
using (SpreadsheetDocument ssd=SpreadsheetDocument.Open(Server.MapPath(@"\ExcelPackageTemplate.xlsx"),true))
{
WorkbookPart wbPart = ssd.WorkbookPart;
WorksheetPart worksheetPart = wbPart.WorksheetParts.First();
SheetData sheetdata = worksheetPart.Worksheet.GetFirstChild<SheetData>();
string[] headerColumns = new string[] { dt.Columns[0].ColumnName, dt.Columns[1].ColumnName,dt.Columns[2].ColumnName };
DocumentFormat.OpenXml.Spreadsheet.Row r = new DocumentFormat.OpenXml.Spreadsheet.Row();
int RowIndexer = 1;
//int colInd=0;
r.RowIndex = (UInt32)RowIndexer;
string test = ColumnName(RowIndexer);
foreach (DataColumn dc in dt.Columns)
{
DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
cell.CellReference = test+RowIndexer;
cell.DataType = CellValues.InlineString;
cell.InlineString = new InlineString(new Text(dc.ColumnName.ToString()));
DocumentFormat.OpenXml.Spreadsheet.CellValue value = new DocumentFormat.OpenXml.Spreadsheet.CellValue();
r.AppendChild(cell);
// colInd++;
}
//r.RowIndex = (UInt32)RowIndexer;
RowIndexer = 2;
foreach (DataRow dr in dt.Rows)
{
DocumentFormat.OpenXml.Spreadsheet.Row Row = new DocumentFormat.OpenXml.Spreadsheet.Row();
string Index = ColumnName(RowIndexer);
Row.RowIndex = (UInt32)RowIndexer;
foreach (object value in dr.ItemArray)
{
DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
cell.DataType = CellValues.InlineString;
cell.InlineString = new InlineString(new Text(value.ToString()));
cell.CellReference = Index+RowIndexer;
// cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(value.ToString());
Row.AppendChild(cell);
}
RowIndexer++;
}
worksheetPart.Worksheet.Save();
wbPart.Workbook.Save();
ssd.Close();