NPOI 导出 excel 所有列,但最后一个列变为空白

NPOI export excel all columns but last become blank

我正在投资 AutoSizeColumn() 的 NPOI Excel 出口。从这个 SO question, I know that when exporting a DataTable to excel, have to write all data inside one column before calling the AutoSizeColumn(). Example: (as from this SO answer:

HSSFWorkbook spreadsheet = new HSSFWorkbook();

DataSet results = GetSalesDataFromDatabase();

//here, we must insert at least one sheet to the workbook. otherwise, Excel will say 'data lost in file'
HSSFSheet sheet1 = spreadsheet.CreateSheet("Sheet1");

foreach (DataColumn column in results.Tables[0].Columns)
{
    int rowIndex = 0;
    foreach (DataRow row in results.Tables[0].Rows)
    {
        HSSFRow dataRow = sheet1.CreateRow(rowIndex);
        dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
        rowIndex++;
    }
    sheet1.AutoSizeColumn(column.Ordinal);
}

//Write the stream data of workbook to the file 'test.xls' in the temporary directory
FileStream file = new FileStream(Path.Combine(Path.GetTempPath(), "test.xls") , FileMode.Create);
spreadsheet.Write(file);
file.Close();

当我打开 test.xls 时,只有最后一列有值。之前的所有专栏都没有任何内容! (但是 each 列的大小已调整。)

仅供参考:1) 我使用 https://www.dotnetperls.com/datatable 中的 GetTable() 中的代码 2) 我正在使用 C#。

When I open the test.xls, only the last column has value. All those previous columns does not have anything in it! (The size of each column is adjusted however.)

那是因为您正在遍历该列,并且在每次迭代时(重新)创建所有行。此行(重新)创建循环有效地用空白行覆盖旧行(设置了之前的单元格值)。因此,除最后一列外的所有列都变为空白。

尝试切换循环顺序,以便先迭代行然后列:

HSSFWorkbook spreadsheet = new HSSFWorkbook();

DataSet results = GetSalesDataFromDatabase();

//here, we must insert at least one sheet to the workbook. otherwise, Excel will say 'data lost in file'
HSSFSheet sheet1 = spreadsheet.CreateSheet("Sheet1");

int rowIndex = 0;
foreach (DataRow row in results.Tables[0].Rows)
{                
  HSSFRow dataRow = sheet1.CreateRow(rowIndex);
  foreach (DataColumn column in results.Tables[0].Columns)
  {
    dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());          
  }
  rowIndex++;
}

for(var i = 0; i< results.Tables[0].Columns.Count; i++)
{
  sheet1.AutoSizeColumn(i);
}

//Write the stream data of workbook to the file 'test.xls' in the temporary directory
FileStream file = new FileStream(Path.Combine(Path.GetTempPath(), "test.xls"), FileMode.Create);
spreadsheet.Write(file);
file.Close();