我有現有的代碼可以使用OpenXML從Excel生成電子表格。它工作正常,但我總是不得不進入電子表格後添加格式。確實openXML(C#)支持生成格式化的數字字段(如1,000,000)
無論如何,我的C#代碼我可以指定,我想要格式化一定數字格式的列)逗號,小數等?
任何指向示例的鏈接都很棒。
這裏是我現在如何保存數據:
public void SetCell<T>(string column, uint rowIndex, T value)
{
SheetData sheetData = _positionSheet;
Cell cell = GetCell(sheetData, column, rowIndex);
string stringValue = value == null ? "" : value.ToString();
cell.CellValue = new CellValue(stringValue);
switch (typeof(T).Name)
{
case "Date":
case "DateTime":
cell.DataType = CellValues.Date;
break;
case "Int32":
cell.DataType = CellValues.Number;
break;
default:
cell.DataType = CellValues.String;
break;
}
}
下面
是GetCell()方法(即使我想這就是對這個問題並不真正相關:
static private Cell GetCell(SheetData sheet, string column, uint rowIndex)
{
Cell cell;
Row row = GetRow(sheet, rowIndex);
if (row.Elements<Cell>().Where(c => c.CellReference.Value == column + rowIndex).Any())
{
cell = row.Elements<Cell>().Where(c => c.CellReference.Value == column + rowIndex).First();
}
else
{
Cell refCell = null;
var comparer = new CellComparer();
foreach (Cell existingCell in row.Elements<Cell>())
{
if (comparer.Compare(existingCell.CellReference.Value, column + rowIndex) > 0)
{
refCell = existingCell;
break;
}
}
cell = new Cell { CellReference = column + rowIndex };
row.InsertBefore(cell, refCell);
}
return cell;
}