• C# NPOI导出Excel 表格宽度自适应,支持中文


     /// <summary>
            /// 转换内存表为Office2007版本以上的EXCEL文件流
            /// </summary>
            /// <param name="sourceTable"></param>
            /// <param name="sheetName"></param>
            /// <param name="dateTimeFormat"></param>
            /// <returns></returns>
            public static MemoryStream DataTableToXLSXStream(DataTable sourceTable, string sheetName = "Sheet1", string dateTimeFormat = "yyyy-MM-dd HH:mm:ss")
            {
                XSSFWorkbook workbook = new XSSFWorkbook();
                WriteReportToXLSXSheet(workbook, sourceTable, sheetName, dateTimeFormat);
                ISheet sheet = workbook.GetSheetAt(0);
                //设置自适应宽度,9为Excel列数,根据需要自已修改
                for (int columnNum = 0; columnNum <= 9; columnNum++)
                {
                    int columnWidth = sheet.GetColumnWidth(columnNum) / 256;
                    //5为开始修改的行数,默认为0行开始
                    for (int rowNum = 5; 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+1;
                            if (columnWidth < length)
                            {
                                columnWidth = length;
                            }
                        }
                    }
                    sheet.SetColumnWidth(columnNum, columnWidth * 256);
                }
                MemoryStream ms = new MemoryStream();
                workbook.Write(ms, true);
                ms.Seek(0, SeekOrigin.Begin);
                return ms;
            }
    View Code

      如需隐藏某列

    sheet.SetColumnHidden(10,true);//隐藏第11列
  • 相关阅读:
    7.1类模板
    异质链表
    8.1多态性
    8.2虚函数
    error: C2664: “zajiao::zajiao(const zajiao &)”: 无法将参数 1 从“const char [12]”转换为“char *”
    #include <QPushButton>
    6.3多重继承
    华为集群后killsql命令和查看mr占用的磁盘空间
    linux的逻辑运算符
    test命令
  • 原文地址:https://www.cnblogs.com/personblog/p/13644214.html
Copyright © 2020-2023  润新知