如何设置“ AutoSize”到Excel工作表列? (NPOI) [英] How to set "AutoSize" to Excel sheet column? (NPOI)

查看:288
本文介绍了如何设置“ AutoSize”到Excel工作表列? (NPOI)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据如何可以在使用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);
 }

但这是行不通的。

推荐答案

以下是一些适用于我的代码,使用您的循环:

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).

这篇关于如何设置“ AutoSize”到Excel工作表列? (NPOI)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆