酷龙王子 2021-12-30 20:27 采纳率: 0%
浏览 1089

C# 使用 npoi 将excel文件 转 pdf成文件

C# 使用 npoi 将excel文件 转 pdf成文件
spire.xls倒是能转 但是收费的 有水印。
使用 npoi 将excel文件 转 pdf成文件 谁有好办法啊 求 转化代码。

  • 写回答

5条回答 默认 最新

  • CSDN专家-showbo 2021-12-31 09:10
    关注

    可以用iTextSharp,代码来源:

             /// <summary>
            /// 生成pdf文件
            /// </summary>
            /// <param name="excelContent">excel文件的字节流</param>
            /// <returns></returns>
            public byte[] Render(byte[] excelContent)
            {
                if (excelContent == null)
                    return null;            
                byte[] result = null;
                MemoryStream stream = new MemoryStream(excelContent);
                HSSFWorkbook hw = new HSSFWorkbook(stream);//创建excel操作对象
                //创建pdf文档对象,设置pdf文档的纸张大小
                Document doc;
                if (_isLandscape)
                {
                    doc = new Document(_pageSize.Rotate());//pdf文档设置为横向
                }
                else
                {
                    doc = new Document(_pageSize);
                }
                doc.SetMargins(0, 0, _marginTop, _marginBottom);//设置文档的页边距
                try
                {
                    ISheet sheet = hw.GetSheetAt(0);//获取excel中的第一个sheet,如果excel中有多个sheet,此处需要进行循环
                    stream = new MemoryStream();
                    PdfWriter pdfWriter = PdfWriter.GetInstance(doc, stream);
                    BaseFont bsFont = BaseFont.CreateFont(_fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);//创建pdf文档字体
                    doc.Open();
                    float[] widths = GetColWidth(sheet);//获取excel中每列的宽度
                    PdfPTable table = new PdfPTable(widths);//设置pdf中表格每列的宽度
                    table.WidthPercentage = _widthPercent;
                    int colCount = widths.Length;
     
                    //通过循环读取excel内容,并将读取的数据写入pdf文档中
                    for (int r = sheet.FirstRowNum; r < sheet.PhysicalNumberOfRows; r++)
                    {
                        IRow row = sheet.GetRow(r);
                        if (row != null)
                        {
                            for (int c = row.FirstCellNum; (c < row.PhysicalNumberOfCells || c < colCount) && c > -1; c++)
                            {
                                if (c >= row.PhysicalNumberOfCells)
                                {
                                    PdfPCell cell = new PdfPCell(new Phrase(""));
                                    cell.Border = 0;
                                    table.AddCell(cell);
                                    continue;
                                }
                                ICell excelCell = row.Cells[c];
                                string value = "";
                                string horAlign = excelCell.CellStyle.Alignment.ToString();
                                string verAlign = excelCell.CellStyle.VerticalAlignment.ToString();
     
     
                                if (excelCell != null)
                                {
                                    value = excelCell.ToString().Trim();
                                    if (!string.IsNullOrEmpty(value))
                                    {
                                        string dataFormat = excelCell.CellStyle.GetDataFormatString();
                                        if (dataFormat != "General" && dataFormat != "@")//数据不为常规或者文本
                                        {
                                            try
                                            {
                                                string numStyle = GetNumStyle(dataFormat);
                                                value = string.Format("{0:" + numStyle + "}", excelCell.NumericCellValue);//如果解析不成功则按字符串处理
                                            }
                                            catch { }
                                        }
                                    }
                                }
     
                                IFont excelFont = excelCell.CellStyle.GetFont(hw);
                                HSSFPalette palette = hw.GetCustomPalette();
                                HSSFColor color = null;
                                Color ftColor = Color.BLACK;
                                short ft = excelFont.Color;
                                color = palette.GetColor(ft);
                                if (color != null && ft != 64)
                                {
                                    byte[] ftRGB = color.RGB;
                                    ftColor = new Color(ftRGB[0], ftRGB[1], ftRGB[2]);
                                }
                                bool isBorder = HasBorder(excelCell);
                                Font pdfFont = new Font(bsFont, excelFont.FontHeightInPoints, excelFont.IsBold ? 1 : 0, ftColor);
                                PdfPCell pdfCell = new PdfPCell(new Phrase(value, pdfFont));
                                List<PicturesInfo> info = sheet.GetAllPictureInfos(r, r, c, c, true);//判断单元格中是否有图片,不支持图片跨单元格
                                 if (info.Count > 0)
                                {
                                    pdfCell = new PdfPCell(Image.GetInstance(info[0].PictureData));
                                }
     
                                short bg = excelCell.CellStyle.FillForegroundColor;
                                color = palette.GetColor(bg);
                                if (color != null && bg != 64)
                                {
                                    byte[] bgRGB = color.RGB;
                                    pdfCell.BackgroundColor = new Color(bgRGB[0], bgRGB[1], bgRGB[2]);
                                }
                                if (!isBorder)
                                {
                                    pdfCell.Border = 0;
     
                                }
                                else
                                {
                                    short bd = excelCell.CellStyle.TopBorderColor;
                                    color = palette.GetColor(bd);
                                    if (color != null && bd != 64)
                                    {
                                        byte[] bdRGB = color.RGB;
                                        pdfCell.BorderColor = new Color(bdRGB[0], bdRGB[1], bdRGB[2]);
                                    }
                                }
     
                                pdfCell.MinimumHeight = row.HeightInPoints;
                                pdfCell.HorizontalAlignment = GetCellHorAlign(horAlign);
                                pdfCell.VerticalAlignment = GetCellVerAlign(verAlign);
     
                                if (excelCell.IsMergedCell)//合并单元格
                                {
                                    int[] span = GetMergeCellSpan(sheet, r, c);
                                    if (span[0] == 1 && span[1] == 1)//合并过的单元直接跳过
                                        continue;
                                    pdfCell.Rowspan = span[0];
                                    pdfCell.Colspan = span[1];
                                    c = c + span[1] - 1;//直接跳过合并过的单元格
                                }
                                table.AddCell(pdfCell);
     
                            }
                        }
                        else
                        {//空行
                            PdfPCell pdfCell = new PdfPCell(new Phrase(""));
                            pdfCell.Border = 0;
                            pdfCell.MinimumHeight = 13;
                            table.AddCell(pdfCell);
                        }
                    }
     
                    doc.Add(table);
                    doc.Close();
                    result = stream.ToArray();
     
                }
                finally
                {
                    hw.Close();
                    stream.Close();
                }
     
                return result;
     
            }
    
    

    img


    有帮助或启发麻烦点下【采纳该答案】,谢谢~~

    评论

报告相同问题?

问题事件

  • 创建了问题 12月30日

悬赏问题

  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多