【发布时间】:2025-12-28 23:30:16
【问题描述】:
我有一个 excel 文件。我想得到这方面的数据。
我使用这个代码。
public static DataTable ConvertToDataTable(ExcelDocument source, bool hasTitle = true)
{
if (source == null)
return null;
// Get range of used data in excel file.
Excel.Range excelCell = source.WorkSheet.UsedRange;
// Get data of range and save it to array.
Object[,] valuesExcel = (Object[,])excelCell.Value2;
if (valuesExcel == null)
return null;
DataTable dataTable = new DataTable();
DataRow dataRow;
// We may have two rows,first for datatable's name and second for datatable's header.
// We check first(datatable's name) is exist.
int startRow = (hasTitle) ? 2 : 1;
int rowIndex;
int columnIndex;
int rowsCount;
int columnsCount;
// Get count of rows.
rowsCount = valuesExcel.GetLength(0);
if (rowsCount != 0)
{
// Get count of columns.
columnsCount = valuesExcel.GetLength(1);
if (columnsCount != 0)
{
for (columnIndex = 1; columnIndex <= columnsCount; columnIndex++)
{
// Create column headrs.
dataTable.Columns.Add(new DataColumn((String)valuesExcel[startRow, columnIndex]));
}
columnsCount = dataTable.Columns.Count;
for (rowIndex = 3; rowIndex <= rowsCount; rowIndex++)
{
// Create new row ,fill it and set cells.
dataRow = dataTable.NewRow();
for (columnIndex = 1; columnIndex <= columnsCount; columnIndex++)
{
// set data for any cells.
dataRow[(String)valuesExcel[startRow, columnIndex]] = valuesExcel[rowIndex, columnIndex];
}
dataTable.Rows.Add(dataRow);
}
}
}
return dataTable;
}
但是rowsCount = valuesExcel.GetLength(0); 和columnsCount = valuesExcel.GetLength(1); 得到空列和行。
例如,我有一个记录 13 行和 6 列的文件。但是当我使用此代码时,我得到一个 rowcount=34 和 columncount=20。
我的文件中的行和列都是空的。
【问题讨论】: