How to set “AutoSize” to Excel sheet column? (NPOI)

别说谁变了你拦得住时间么 提交于 2019-12-30 17:26:13

问题


According to How can columns be set to 'autosize' in Excel documents created with NPOI? I did so:

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

But it doesn't work. How to do right?


回答1:


Here is some code that is working for me, using your loops:

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

If it doesn't work for you then we need to look at the kind of data you're pushing out, see if there's a difference that makes a difference there. (I'm assuming that we don't have a version discrepancy or anything like that).




回答2:


Just to add an extra bit to the answer by YellowFog. I found that I had to add all data to the sheet, then iterate through the columns, setting AutoSizeColumn(idx) for this to work correctly.



来源:https://stackoverflow.com/questions/6055519/how-to-set-autosize-to-excel-sheet-column-npoi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!