如何将“AutoSize”设置为Excel工作表列? (NPOI)

时间:2011-05-19 07:55:52

标签: c# .net excel npoi

根据How can columns be set to 'autosize' in Excel documents created with NPOI?,我这样做了:

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

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

2 个答案:

答案 0 :(得分:17)

以下是一些使用循环的代码:

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

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

答案 1 :(得分:2)

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