13

根据如何在使用 NPOI 创建的 Excel 文档中将列设置为“自动调整大小”?我这样做了:

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

但它不起作用。怎么做才对?

4

2 回答 2

26

这是一些对我有用的代码,使用您的循环:

    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();

如果它对您不起作用,那么我们需要查看您推出的数据类型,看看是否有差异在那里产生了影响。(我假设我们没有版本差异或类似的东西)。

于 2011-07-11T14:37:47.997 回答
3

只是为了在 YellowFog 的答案中增加一点。我发现我必须将所有数据添加到工作表中,然后遍历列,设置 AutoSizeColumn(idx) 以使其正常工作。

于 2016-08-11T14:06:32.587 回答