.NET使用NPOI(3) - 適応列幅

       パートIは NPOI輸出Excelの機能の使用が記載されているが、我々はいくつかの欠点があることがわかりました

       私たちは、次のように完全なコードは、「フルサポート」の幅は、テーブル内幅に合わせていなかった場合は、私たちが幅を設定することができます表示されませんでした。

public ActionResult Index()
{
    //声明工作表
    HSSFWorkbook wk = new HSSFWorkbook();
    ISheet sheet = wk.CreateSheet("工作汇报1");

    //设置表头
    IRow cells = sheet.CreateRow(0);
    cells.CreateCell(0).SetCellValue("编号");
    cells.CreateCell(1).SetCellValue("任务名称");
    cells.CreateCell(2).SetCellValue("核心内容");
    //添加10行数据
    for (int i = 0; i < 10; i++)
    {
        IRow rowtemp = sheet.CreateRow(i + 1); //循环行
        rowtemp.CreateCell(0).SetCellValue(i + 1);
        rowtemp.CreateCell(1).SetCellValue("任务名称" + i);
        rowtemp.CreateCell(2).SetCellValue("此任务主要是处理..." + i);
    }

    //设置自适应宽度
    for (int columnNum = 0; columnNum <= 10; columnNum++)
    {
        int columnWidth = sheet.GetColumnWidth(columnNum) / 256;
        for (int rowNum = 1; rowNum <= sheet.LastRowNum; rowNum++)
        {
            IRow currentRow = sheet.GetRow(rowNum);
            if (currentRow.GetCell(columnNum) != null)
            {
                ICell currentCell = currentRow.GetCell(columnNum);
                int length = Encoding.Default.GetBytes(currentCell.ToString()).Length;
                if (columnWidth < length)
                {
                    columnWidth = length;
                }
            }
        }
        sheet.SetColumnWidth(columnNum, columnWidth * 256);
    }

    //导出excel,名字可自定义
    MemoryStream memoryStream = new MemoryStream();
    wk.Write(memoryStream);
    memoryStream.Seek(0, SeekOrigin.Begin);
    return File(memoryStream, "application/vnd.ms-excel", "工作汇报.xls");
}

       トップ上のコードの実行は、「//セットの適応の幅」セクションに注意を払うが、我々は結果を見て:

公開された109元の記事 ウォン称賛42 ビュー570 000 +

おすすめ

転載: blog.csdn.net/sinat_28984567/article/details/94359244