函数实现:
private static void FillData(string path, string sheetName)
{
using (SpreadsheetDocument document = SpreadsheetDocument.Open(
path, true))
{
// find sheets by sheet name
IEnumerable<Sheet> sheets = document.WorkbookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == sheetName);
if (sheets.Count() == 0)
{
// The specified worksheet does not exist.
return;
}
WorksheetPart worksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(sheets.First().Id);
Worksheet worksheet = worksheetPart.Worksheet;
SheetData sheetData = worksheet.GetFirstChild<SheetData>();
// fill data to Cell F4
Row row1 = new Row()
{
RowIndex = (UInt32Value)4U,
Spans = new ListValue<StringValue>() { InnerText = "5:6" }
};
//CellFormula cellformula = new CellFormula();
//cellformula.Text = "SUM(A1:A2)";
//Cell cell = new Cell()
//{
// CellReference = "F4",
// DataType = new EnumValue<CellValues>(CellValues.Number),
// CellFormula = cellformula
//};
Cell cell = new Cell() { CellReference = "E4" };
CellFormula cellformula = new CellFormula();
cellformula.Text = "SUM(A1,C5)";
CellValue cellValue = new CellValue();
cellValue.Text = "0";
cell.Append(cellformula);
cell.Append(cellValue);
Cell cell1 = new Cell() { CellReference = "F4" };
CellValue cellValue1 = new CellValue();
cellValue1.Text = "222";
cell1.Append(cellValue1);
// create formula in E4
row1.Append(cell);
// fill data to F4
row1.Append(cell1);
// fill data to Cell C5
Row row2 = new Row() { RowIndex = (UInt32Value)5U };
Cell cell2 = new Cell() { CellReference = "C5" };
CellValue cellValue2 = new CellValue();
cellValue2.Text = "111";
cell2.Append(cellValue2);
row2.Append(cell2);
// append rows to SheetData elment
sheetData.Append(row1);
sheetData.Append(row2);
// save worksheet
worksheet.Save();
}
}
可运行项目下载:
http://download.csdn.net/detail/songpengpeng20100202/3925553