04 06 2025

上文提到了word模版填充数据导出,这篇介绍下excel模版的数据填充。


笔者这里采用的是类似于lable标签替换的形式,找到每个cell单元格的值,并且替换掉即可。这点应该没啥比较大的难度,比较特殊的是,表格模版中有个列表,


这个列表的处理可能相对来说比较耗时。


模版如下图: 注意截图部分的表格




部分核心代码如下:

 /// <summary>
    /// sheet 为 excel表格中的sheet对象
    /// jobject 为数据源对象 具体可根据情况自行修改
    /// </summary>
    /// <param name="sheet"></param>
    /// <param name="jobject"></param>
    /// <returns></returns>
    private static string FillData(ISheet sheet, JObject jobject)
    {
      string resultStr = string.Empty;
      try
      {
        //excel表格中 标记的 dataset中的表名称
        string tableName = string.Empty;
        //excel表格中 标记的 dataset表中对应的字段名称
        string columnName = string.Empty;
        //标记当前多集合datatable循环到第几行了
        int dtCurrentRowNum = 0;
        //标记当前多集合datatable 取值的当前列号
        //int dtCurrentColumnNum = 0;
        //标记是否需要多次循环
        bool isMuti = false;
        //标记 多循环集合中需要取值的 下一行的cell列号
        List<int> dbTitle = new List<int>();
        Dictionary<int, string> dicTitle = new Dictionary<int, string>();
        //标记 当前cell中变量值
        string[] cellStr = null;
        var rowCount = sheet.LastRowNum;
        for (var i = sheet.FirstRowNum; i <= rowCount; i++)
        {
          var row = sheet.GetRow(i);
          if (row == null) continue;
          ICell cellValue = null;
          for (int j = row.FirstCellNum; j < row.LastCellNum; j++)
          {
            cellValue = row.GetCell(j);
            string ced = cellValue.ToString();
            if (cellValue.ToString().Contains("{{") && cellValue.ToString().Contains("}}"))
            {
              if (cellValue.ToString().Replace("{{", "").Replace("}}", "").Contains("."))
              {
                //excel列表数据
                cellStr = cellValue.ToString().Replace("{{", "").Replace("}}", "").Split('.');
                //数据源中的表名称
                tableName = cellStr[0];
                //数据源中的列名称
                columnName = cellStr[1];
                if (jobject.SelectToken(tableName).Value<JArray>() == null)
                {
                  // resultStr = columnName + "字段未配置";
                  // break;
                }
                else
                {
                  JArray jArray = (JArray)jobject[tableName];
                  //表名称下的第几行(当前行)数据集合
                  JObject tmpJobject = (JObject)jArray[dtCurrentRowNum];
                  if (tmpJobject.Property(columnName) != null)
                     cellValue.SetCellValue(tmpJobject[columnName].ToString());
                  else
                    cellValue.SetCellValue("");
                  if (!isMuti) isMuti = true;
                  //把列下标 和列名 放入一个字典中
                  dicTitle.Add(j, columnName);
                }
              }
              else
              {
                //excel中 非列表数据
                columnName = cellValue.ToString().Replace("{{", "").Replace("}}", "");
                if (jobject.Property(columnName) == null)
                {
                  // resultStr = columnName + "字段未配置";
                  //break;
                  if (columnName == "tjdw")
                  {
                    if (jobject.Property("field_zfrrk__c") != null)
                    {
                      if (jobject["field_zfrrk__c"].ToString() == "option1")
                      {
                        cellValue.SetCellValue(jobject["companyName__c__r"].ToString());
                        if (isMuti) isMuti = false;
                      }
                      else
                      {
                        cellValue.SetCellValue(jobject["field_YpI8g__c__r"].ToString());
                        if (isMuti) isMuti = false;
                      }
                    }
                  }
                }
                else
                {
                  if (columnName == "dzbg__c")
                  {
                    if (jobject.Property("dzbg__c") != null)
                    {
                      if (jobject["dzbg__c"].ToString() == "option1")
                      {
                        cellValue.SetCellValue("是");
                        if (isMuti) isMuti = false;
                      }
                      else
                      {
                        cellValue.SetCellValue("否");
                        if (isMuti) isMuti = false;
                      }
                    }
                  }
                }
              }
            }
            else if (string.IsNullOrWhiteSpace(cellValue.ToString()))
            {
              //excel中列表 由于在调用该方法之前 先按照数据源的行数 
              //在此 列表中插入了新行 这些新插入的行 cellvalue 都为空
              // excel 中的列表 并且是上面新插入的行
              if (isMuti)
              {
                if (j == 2)
                  //写入序号
                  cellValue.SetCellValue(dtCurrentRowNum + 1);
              }
              if (dicTitle.ContainsKey(j))
              {
                if (((JArray)jobject[tableName]).Count > dtCurrentRowNum)
                {
                  if (((JObject)((JArray)jobject[tableName])[dtCurrentRowNum]).Property(dicTitle[j]) != null)
                   cellValue.SetCellValue(((JArray)jobject[tableName])[dtCurrentRowNum][dicTitle[j]].ToString());
                  else
                    cellValue.SetCellValue("");
                  if (!isMuti) isMuti = true;

                }
              }
            }
          }
          if (isMuti)
            dtCurrentRowNum++;
        }
      }
      catch (Exception ex)
      {
      }
      return resultStr;
    }

      ///合并单元格
         public IWorkbook EditorExcel(string savePath, IWorkbook workbook, OperationExcel oe)
        {
               try
            {
                if (insertRowCount == 0)
                {
                    //合并单元格
                    CellRangeAddress region = new CellRangeAddress(10, 12 + insertRowCount, 1, 1);
                    workbook.GetSheetAt(0).AddMergedRegion(region);
                    CellRangeAddress region3 = new CellRangeAddress(13 + insertRowCount, 13 + insertRowCount, 3, 6);
                    workbook.GetSheetAt(0).AddMergedRegion(region3);
                    return workbook;
                }
            }
            catch (Exception ex)
            { 
                    throw new Exception(ex.Message);
            }
        }


 /// <summary>
    /// Excel转成Pdf文件
    /// </summary>
    /// <param name="sourceFileUrl"></param>
    /// <param name="targetFileUrl"></param>

    public void Excel2Pdf(string sourceFileUrl, string targetFileUrl)
    {
      Workbook wb = new Workbook(sourceFileUrl);
      Aspose.Cells.Style style = wb.Styles[wb.Styles.Add()];
      style.ShrinkToFit = true;
      int cnt = wb.Worksheets.Count;
      for (int i = 0; i < cnt; i++)
      {
        Worksheet wbSheet = wb.Worksheets[i];
        wbSheet.IsPageBreakPreview = true;
        wbSheet.PageSetup.FooterMargin = 0;
        wbSheet.PageSetup.HeaderMargin = 0;
        wbSheet.PageSetup.RightMargin = 1;
        wbSheet.PageSetup.LeftMargin = 1;
        // wbSheet.PageSetup.Orientation = PageOrientationType.Landscape;
        wbSheet.PageSetup.CenterHorizontally = true;//水平居中
               // 保证excel形成的pdf 保持A4格式  支持分页   否则可能会pdf特别长 窄 
              wbSheet.PageSetup.PaperSize =PaperSizeType.PaperA4;
           wbSheet.PageSetup.FitToPagesWide = 1;
           wbSheet.PageSetup.FitToPagesTall = 50;
      }
      wb.Save(targetFileUrl, Aspose.Cells.SaveFormat.Pdf);
    }

    /// pdf 指定字体打水印(文字水印)
  public void AddWaterMarkingToPdf(string sourceFileUrl, string targetFileUrl, string waterMarkingStr)
        {
            PdfReader pdfReader = null;
            PdfStamper pdfStamper = null;
            try
            {
                pdfReader = new PdfReader(sourceFileUrl);
                pdfStamper = new PdfStamper(pdfReader, new FileStream(targetFileUrl, FileMode.Create));
                int total = pdfReader.NumberOfPages + 1;
                iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1);
                float width = psize.Width;
                float height = psize.Height;
                PdfContentByte content;
                BaseFont font = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\SIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                PdfGState gs = new PdfGState();
                for (int i = 1; i < total; i++)
                {
                    content = pdfStamper.GetOverContent(i);//在内容上方加水印
                    //content = pdfStamper.GetUnderContent(i);//在内容下方加水印
                    //透明度
                    gs.FillOpacity = 0.3f;
                    content.SetGState(gs);
                    //content.SetGrayFill(0.3f);
                    //开始写入文本
                    content.BeginText();
                    content.SetColorFill(iTextSharp.text.BaseColor.LIGHT_GRAY);
                    content.SetFontAndSize(font, 100);
                    content.SetTextMatrix(0, 0);
                    content.ShowTextAligned(Element.ALIGN_CENTER, waterMarkingStr, width / 2 - 50, height / 2 - 50, 55);
                    //content.SetColorFill(BaseColor.BLACK);
                    //content.SetFontAndSize(font, 8);
                    //content.ShowTextAligned(Element.ALIGN_CENTER, waterMarkName, 0, 0, 0);
                    content.EndText();
                }
                //删除job服务器上的pdf文件
                if (File.Exists(targetFileUrl)) File.Delete(targetFileUrl);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                     if (pdfStamper != null)
               pdfStamper.Close();
                     if (pdfReader != null)
                 pdfReader.Close();
            }
        }


完成源码下载地址:


链接:https://pan.baidu.com/s/1hyQPoYP1kx-k36kQLHh0kQ 


提取码:qgsz



.NET C# JAVA 基础交流群 1095936339 欢迎入群 交流