我已经预先定义了 excel 格式,我需要将数据传递给 excel。我能够获得特定的工作表。但不知道如何将数据传递给单元格。
var excelDocument = new ExcelDocument();
var fileName = Guid.NewGuid();
string filePath = HttpContext.Current.Server.MapPath("~/Uploads/TemplateFiles/test.xlsx");
using (SpreadsheetDocument document =
SpreadsheetDocument.Open(filePath, false))
{
WorkbookPart workbookPart = document.WorkbookPart;
Workbook workbook = document.WorkbookPart.Workbook;
string sheetName = workbookPart.Workbook.Descendants<Sheet>().ElementAt(1).Name;
IEnumerable<Sheet> sheets = document.WorkbookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == "Census Template for Import");
if (sheets.Count() == 0)
{
// The specified worksheet does not exist.
return null;
}
WorksheetPart worksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(sheets.First().Id);
SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();
var excelRows = sheetData.Descendants<DocumentFormat.OpenXml.Spreadsheet.Row>().ToList();
int rowindex = 10;
foreach (var item in census)
{
//how to write the data in cell
rowindex++;
}
worksheetPart.Worksheet.Save();
workbookPart.Workbook.Save();
document.Close();
//worksheetPart.Worksheet.Save();
}
return filePath;
Run Code Online (Sandbox Code Playgroud)
这是一种获取单元格或添加新单元格的方法,如果单元格不存在,当您知道行和列索引时。
注意:
RowIndex一的Row应创建行的过程中被初始化CellReference一的Cell应创建细胞的过程中被初始化如果RowIndex或CellReference为空,则将抛出 NullReferenceException。
private Cell InsertCell(uint rowIndex, uint columnIndex, Worksheet worksheet)
{
Row row = null;
var sheetData = worksheet.GetFirstChild<SheetData>();
// Check if the worksheet contains a row with the specified row index.
row = sheetData.Elements<Row>().FirstOrDefault(r => r.RowIndex == rowIndex);
if (row == null)
{
row = new Row() { RowIndex = rowIndex };
sheetData.Append(row);
}
// Convert column index to column name for cell reference.
var columnName = GetExcelColumnName(columnIndex);
var cellReference = columnName + rowIndex; // e.g. A1
// Check if the row contains a cell with the specified column name.
var cell = row.Elements<Cell>()
.FirstOrDefault(c => c.CellReference.Value == cellReference);
if (cell == null)
{
cell = new Cell() { CellReference = cellReference };
if (row.ChildElements.Count < columnIndex)
row.AppendChild(cell);
else
row.InsertAt(cell, (int)columnIndex);
}
return cell;
}
Run Code Online (Sandbox Code Playgroud)
在这里你会找到GetExcelColumnName()方法的代码。
我遇到了与您相同的问题,这篇文章如何:将文本插入电子表格文档的单元格中 (Open XML SDK)。我想您需要将一个新的 Cell 对象插入到工作表中,然后将指定的数据(假设它是一个字符串或它已经被转换为字符串)插入到该单元格中。
| 归档时间: |
|
| 查看次数: |
21498 次 |
| 最近记录: |