首页 > 编程语言 >C# NPOI自适应宽度不支持中文解决方案

C# NPOI自适应宽度不支持中文解决方案

时间:2023-08-07 15:04:54浏览次数:32  
标签:row1 cellStyle rowtemp C# 解决方案 NPOI item CreateCell SetCellValue


NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            ////创建一个工作薄 sheet
            ISheet sheet1 = book.CreateSheet("Sheet1");
            //  创建数据行 0代表是在第几行创建 变量 给sheet1添加第一行的头部标题
            IRow row1 = sheet1.CreateRow(0);
            //设置第一行的高度   【Height的单位是1/20个点】,所以Height的值永远是HeightInPoints【HeightInPoints的单位是点】的20倍
            row1.Height = 25 * 20;
            var font = book.CreateFont();//创建字体
            font.Boldweight = (short)FontBoldWeight.Bold;
            //font.FontHeightInPoints = 18;//字体大
            font.Color = (short)HSSFColor.White.Index;
            ICellStyle cellStyle = book.CreateCellStyle();//创建样式
            cellStyle.SetFont(font);
            cellStyle.Alignment = HorizontalAlignment.Center;
            cellStyle.VerticalAlignment = VerticalAlignment.Center;
            cellStyle.WrapText = true;//自动换行
            cellStyle.FillPattern = FillPattern.SolidForeground;//填充的模式,可以是网格、花式等。如果需要填充单色,请使用:SOLID_FOREGROUND
            cellStyle.FillForegroundColor = HSSFColor.CornflowerBlue.Index; //背景色
            cellStyle.BorderLeft = BorderStyle.Thin;
            cellStyle.LeftBorderColor = (short)HSSFColor.White.Index;
            cellStyle.BorderRight = BorderStyle.Thin;
            cellStyle.RightBorderColor = (short)HSSFColor.White.Index;
            cellStyle.BorderTop = BorderStyle.Thin;
            cellStyle.TopBorderColor = (short)HSSFColor.White.Index;
            cellStyle.BorderBottom = BorderStyle.Thin;
            cellStyle.BottomBorderColor = (short)HSSFColor.White.Index;

            ////创建单元格 并且赋值 
            row1.CreateCell(0).SetCellValue("订单号");
            row1.CreateCell(1).SetCellValue("分类");
            row1.CreateCell(2).SetCellValue("用户编号");
            row1.CreateCell(3).SetCellValue("账户");
            row1.CreateCell(4).SetCellValue("收入/支出");
            row1.CreateCell(5).SetCellValue("交易前金额");
            row1.CreateCell(6).SetCellValue("交易余额");
            row1.CreateCell(7).SetCellValue("交易后金额");
            row1.CreateCell(8).SetCellValue("交易类型");
            row1.CreateCell(9).SetCellValue("交易时间");
            row1.CreateCell(10).SetCellValue("交易说明");
            for (int j = 0; j < 11; j++)
            {
                //headerRow.Cells[i].CellStyle;
                row1.GetCell(j).CellStyle = cellStyle;
            }

            //将数据逐步写入sheet1各个行
            int i = 0;
            foreach (var item in collection.FundDetailList)
            {

                i++;
                NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i);
                rowtemp.CreateCell(0).SetCellValue(item.OrderId);
                rowtemp.CreateCell(1).SetCellValue(item.Category);
                rowtemp.CreateCell(2).SetCellValue(item.UserId);
                rowtemp.CreateCell(3).SetCellValue(item.AccountType.ToString().Equals("Bonus", StringComparison.OrdinalIgnoreCase) ? "奖金账户" : item.AccountType.ToString().Equals("FillMoney", StringComparison.OrdinalIgnoreCase) ? "充值账户" : item.AccountType.ToString().Equals("Freeze", StringComparison.OrdinalIgnoreCase) ? "冻结账户" : string.Empty);
                rowtemp.CreateCell(4).SetCellValue(item.PayType.ToString().Equals("Payin", StringComparison.OrdinalIgnoreCase) ? "收入" : item.PayType.ToString().Equals("Payout", StringComparison.OrdinalIgnoreCase) ? "支出" : string.Empty);
                rowtemp.CreateCell(5).SetCellValue(item.BeforeBalance.ToString("N2"));
                rowtemp.CreateCell(6).SetCellValue(item.PayMoney.ToString("N2"));
                rowtemp.CreateCell(7).SetCellValue(item.AfterBalance.ToString("N2"));
                rowtemp.CreateCell(8).SetCellValue(item.AiOrderId);
                rowtemp.CreateCell(9).SetCellValue(item.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"));
                rowtemp.CreateCell(10).SetCellValue(item.Summary);
            }
           
for (int j = 0; j < 11; j++)
{
	//自动调整列的宽度
	sheet1.AutoSizeColumn(j);
	int columnWidth = sheet1.GetColumnWidth(j) / 256;
	for (int rowNum = 1; rowNum <= sheet1.LastRowNum; rowNum++)
	{
	IRow currentRow = sheet1.GetRow(rowNum);
	if (currentRow.GetCell(j) != null)
                {
                    ICell currentCell = currentRow.GetCell(j);
                    int length = Encoding.UTF8.GetBytes(currentCell.ToString()).Length;
                    if (columnWidth < length + 3)
                    {
                        columnWidth = length + 3;
                    }
                }
            }
            sheet1.SetColumnWidth(i, columnWidth * 256);
	}
}
    // 写入到客户端 
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            ms.Seek(0, SeekOrigin.Begin);
            return File(ms, "application/vnd.ms-excel", string.Format("{0}.xls", DateTime.Now.ToString("yyyy-MM-dd")));

实例:

//列宽自适应,只对英文和数字有效  maxColunm为最大列数

for (int i = 0; i <= maxColumn; i++)

{

   sheet.AutoSizeColumn(i);

}

,然后对比本列的长度,取最大值

for (int columnNum = 0; columnNum <= maxColumn; 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.UTF8.GetBytes(currentCell.ToString()).Length;

           if (columnWidth < length)

           {

               columnWidth = length;

           }

       }

   }

   sheet.SetColumnWidth(columnNum, columnWidth * 256);

}

标签:row1,cellStyle,rowtemp,C#,解决方案,NPOI,item,CreateCell,SetCellValue
From: https://blog.51cto.com/jition/6993880

相关文章

  • linux GCC升级版本
    一、查看gcc版本首先查看当前gcc版本:gcc-v[mpshen@bigdata01~]$gcc-vUsingbuilt-inspecs.COLLECT_GCC=gccCOLLECT_LTO_WRAPPER=/usr/local/gcc/libexec/gcc/x86_64-unknown-linux-gnu/4.9.2/lto-wrapperTarget:x86_64-unknown-linux-gnuConfiguredwith:./configure......
  • 云迁移解决方案
    云迁移是指将应用程序和数据从一个位置(通常是公司自有的现场(“本地”服务器)迁移到公有云提供商的服务器的过程,但也指在不同的云之间进行迁移的过程。云迁移的主要优势包括降低IT成本和提高性能,但也存在安全性、便利性和其他优势。是什么推动了云迁移攀登成功行列的组织将尝试主动......
  • 视频融合平台视频汇聚平台LiteCVR出现s3ds挂载无法储存反馈解决方案
    LiteCVR平台采用了云边端一体化架构,可以实现海量视频资源的轻量级接入。它支持多种协议和设备类型的兼容性,并提供视频直播、录像、回放、检索、云存储、级联和告警等功能。我们曾在之前的文章中详细介绍了LiteCVR平台的云存储功能和挂载方法。如果您对此感兴趣,可以查阅我们以前的文......
  • 浅谈PLC程序命名3大通用规则
    导读工程师在编写PLC程序时,可能需要对项目中的程序块、变量表、单一背景数据块、全局DB块等命名。在博途软件中支持中文和英文的命名。但是一旦程序量比较大,命名可能就会出现混乱的现象。针对命名,只要读者遵循相关命名规则就不易发生混乱。本文以博途软件为例进行探讨。01......
  • FP6276兼容G5177C,高效5V2A同步PWM升压DC转换器
    FP6276是一款电流模式同步升压型DC-DC转换器,pwm/psm控制。它的pwm电路,内置55mΩ高侧开关和55mΩ低侧开关使该调节器具备高节能。内部补偿网络也最大限度地减少多达6个外部元件数量。误差放大器的非反相输入端连接到一个0.6v精度参考电压和内部软启动功能可降低浪涌电流。FP6276是......
  • choices参数的使用
    choices参数的使用choices它是ORM中常用字段中的参数 作用:针对于一些字段它的情况能够被列举完,像这样的字段,我们在表中存储的时候一般使用choices参数案例classCustomer(models.Model):"""客户表"""qq=models.CharField(verbose_name='qq',max_len......
  • 关于引用elementui中的el-date-picker组件
    最近有一个需求要用到elementui中的日期选择器组件,但是elementui中的不太满足,在网上找到一个引用里面的组件的教程https://blog.csdn.net/mouday/article/details/103932261但是引用完成后报错Moduleparsefailed:Unexpectedtoken(65:6)Youmayneedanappropriateloader......
  • Siemens 西门子S7-200SMART PLC八盏灯交替闪烁程序设计
    在学习PLC时,接触很多指令,其中功能指令中的传送指令,传送指令是传送地址或数值,那么对于BOOL型变量是否可以使用呢?这是一个思考的问题,在本文章就给大家详细分析传送指令如何对位进行控制和设计程序。一、传送指令(说明)单个传送指令(把IN数据传送至OUT数据地址)传送存储区大小可分......
  • ubuntu wkhtmltopdf 新增Calibri字体
    最近使用wkhtmltopdf将html转为PDF时,在html中使用了Calibri字体,但转换为PDF后,PDF中使用的字体却不是Calibri,,怀疑是转PDF的ubuntu服务器上没有Calibri字体使用locatefont|grep alibri试了一下,没有返回值,说明该服务器上真的没有这个字体,考虑安装一下知识点:1.ubuntu可以与windo......
  • 国标GB28181视频平台LntonGBS(源码版)国标平台出现录像无法播放并存在RTMP重复推流现象
    LntonGBS国标视频云服务通过支持国标GB28181协议,实现了设备接入、实时监控直播、录像、语音对讲、云存储、告警、级联等功能。同时,它还支持将接入的视频流以多种格式(包括RTSP、RTMP、FLV、HLS、WebRTC)进行全终端、全平台分发,实现了无插件播放在Web浏览器、手机浏览器、微信端、PC客......