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

但这是行不通的。怎么办对不对?

最佳答案

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

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

如果这对您不起作用,那么我们需要查看您要提供的数据类型,看看是否存在差异,这些差异会有所不同。 (我假设我们没有版本差异或类似的东西)。

关于c# - 如何将 "AutoSize"设置为Excel工作表列? (NPOI),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6055519/

10-09 03:53