gpt4 book ai didi

c# - Office Open XMl SDK 将数字写入工作表

转载 作者:太空狗 更新时间:2023-10-29 17:52:07 27 4
gpt4 key购买 nike

我正在尝试将数据表中的数字写入数据表 - 不幸的是,这没有按预期工作,例如。 G。数据表已损坏。

我正在使用以下代码:

private void AddDataToSheet(ExcelViewData data, SheetData sheetData)
{
var excelData = data.WriteableDataTable;

// this returns a datatable
// the numbers have a format like "8,1" "8,0" etc.
for (int i = 0; i < excelData.Rows.Count; i++)
{
Row row = new Row();
//row.RowIndex = (UInt32)i;
for (int c = 0; c < excelData.Columns.Count; c++)
{
Cell cell = new Cell();
CellValue cellvalue = new CellValue();
//cell.CellReference = SharedMethods.GetExcelColumnName(i + 1) + (c + 1).ToString();
cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.Number;
cellvalue.Text = excelData.Rows[i][c].ToString().Replace(",",".");
cell.Append(cellvalue);
row.Append(cell);
}

sheetData.Append(row);
}
}

知道为什么会失败吗?我似乎有多个使用相同方法的教程。

最佳答案

试试这个方法:

public void InsertDataTableIntoExcel(SpreadsheetDocument _excelDoc, SheetData    SheetData,  DataTable excelData, int rowIndex = 1)
{
if (_excelDoc != null && SheetData != null)
{
if (excelData.Rows.Count > 0)
{
try
{
uint lastRowIndex = (uint)rowIndex;
for (int row = 0; row < excelData.Rows.Count; row++)
{
Row dataRow = GetRow(lastRowIndex, true);
for (int col = 0; col < excelData.Columns.Count; col++)
{
Cell cell = GetCell(dataRow, col + 1, lastRowIndex);

string objDataType = excelData.Rows[row][col].GetType().ToString();
//Add text to text cell
if (objDataType.Contains(TypeCode.Int32.ToString()) || objDataType.Contains(TypeCode.Int64.ToString()) || objDataType.Contains(TypeCode.Decimal.ToString()))
{
cell.DataType = new EnumValue<CellValues>(CellValues.Number);
cell.CellValue = new CellValue(objData.ToString());
}
else
{
cell.CellValue = new CellValue(objData.ToString());
cell.DataType = new EnumValue<CellValues>(CellValues.String);
}
}
lastRowIndex++;
}
}
catch (OpenXmlPackageException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
else
{
OpenXmlPackageException openEx = new OpenXmlPackageException("No data from datatable");
throw openEx;
}
}
else
{
OpenXmlPackageException openEx = new OpenXmlPackageException("Workbook not found");
throw openEx;
}
}

关于c# - Office Open XMl SDK 将数字写入工作表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16607063/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com