的Office Open XML SDK写的数字来表 [英] Office Open XMl SDK Writing Numbers to Sheet
本文介绍了的Office Open XML SDK写的数字来表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图写禾从数据表数字到数据表 - 不幸的是,预计今年不工作,即G。 。数据表已损坏
I am trying wo write Numbers from a DataTable to an Datasheet - unfortunately, this does not work as expected, e. g. the DataSheet is corrupted.
我使用下面的代码:
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);
}
}
任何想法,为什么失败?我好像用同样的方法多教程
Any Idea why this fails? I have seem multiple tutorials with the same approach.
推荐答案
试试这个方法:
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;
}
}
这篇关于的Office Open XML SDK写的数字来表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文