[WeChat Mini Program] Export Excel reports and share them, use the xlsx library to generate Excel, use echars to insert charts, and use pdfmake to export to PDF files

Generate EXCEL

To export and share an Excel report in the WeChat applet, you can use a third-party library xlsxto generate an Excel file, use wx.saveFilethe method to save the file locally, and then use wx.shareFilethe method to share the file.

The following is a sample code that demonstrates how to export and share an Excel report in the WeChat applet:

  1. First, install the dependent libraries xlsx, you can use npm to install:
npm install xlsx
  1. Introduce the library into the applet page xlsxand define a method to export Excel reports:
// 引入依赖库
const XLSX = require('xlsx');

// 定义导出 Excel 报表的方法
function exportExcel(data, filename) {
    
    
  const workbook = XLSX.utils.book_new();
  const sheet = XLSX.utils.aoa_to_sheet(data);

  XLSX.utils.book_append_sheet(workbook, sheet, 'Sheet1');

  const excelBuffer = XLSX.write(workbook, {
    
     bookType: 'xlsx', type: 'array' });
  const filePath = `${
      
      wx.env.USER_DATA_PATH}/${
      
      filename}.xlsx`;

  wx.saveFile({
    
    
    tempFilePath: filePath,
    filePath: filePath,
    success: function(res) {
    
    
      const savedFilePath = res.savedFilePath;

      wx.shareFile({
    
    
        filePath: savedFilePath,
        success: function(res) {
    
    
          console.log('分享成功');
        },
        fail: function(error) {
    
    
          console.log('分享失败', error);
        }
      });
    },
    fail: function(error) {
    
    
      console.log('保存文件失败', error);
    }
  });
}

In the above example code, we requireintroduced xlsxthe library through the statement. Then, a method named is defined exportExcel, which accepts two parameters: datathe data to be exported and filenamethe file name of the exported file.

In exportExcelthe method, we use xlsxthe library to convert the data to Excel format and use XLSX.writethe method to write the workbook into an array. Then, use wx.saveFilethe method to save the array to a local file, and wx.shareFilethe method to share the file.

Next, you can call exportExcelthe method to export the Excel report and share the file:

// 示例数据
const data = [
  ['姓名', '年龄', '性别'],
  ['张三', 25, '男'],
  ['李四', 30, '女'],
  ['王五', 28, '男']
];

// 调用导出 Excel 报表的方法
exportExcel(data, '报表');

In the above example, we defined an dataarray named which contains the data to be exported. Then, call exportExcelthe method to export the Excel report and specify the file name '报表'.

Please note that the above sample code is for reference only, and the specific implementation may need to be adjusted according to your actual needs.

Insert summaries and charts

Use echartsthe library to generate charts.

The following is a sample code that demonstrates how to export an Excel report and insert a chart into the summary in the WeChat applet:

  1. First, install the dependent libraries xlsxand echarts, you can use npm to install:
npm install xlsx echarts
  1. xlsxIntroduce the and library into the applet page echarts, and define a method to generate chart data:
// 引入依赖库
const XLSX = require('xlsx');
const echarts = require('echarts');

// 定义生成图表数据的方法
function generateChartData() {
    
    
  const xAxisData = ['张三', '李四', '王五', '赵六'];
  const seriesData = [85, 90, 95, 80];

  return {
    
    
    xAxis: {
    
    
      type: 'category',
      data: xAxisData
    },
    yAxis: {
    
    
      type: 'value'
    },
    series: [{
    
    
      data: seriesData,
      type: 'bar'
    }]
  };
}

In the above example code, we requireintroduced xlsxthe and echartslibraries through the statement. generateChartDataThen, a method called is defined , which is used to generate the data for the chart.

In generateChartDatathe method, we define the xAxisDataand seriesDataarrays, which represent the x-axis and y-axis data of the chart respectively. This data is then assembled into an object that contains the chart's configuration information.

Next, you can use echartsthe library to generate the chart and insert the chart data into the summary in the Excel file:

// 定义导出 Excel 报表的方法
function exportExcel(data, filename) {
    
    
  const workbook = XLSX.utils.book_new();
  const sheet = XLSX.utils.aoa_to_sheet(data);

  // 生成图表数据
  const chartData = generateChartData();

  // 创建 chart sheet
  const chartSheet = XLSX.utils.aoa_to_sheet([
    ['姓名', '成绩'],
    ['张三', chartData.series[0].data[0]],
    ['李四', chartData.series[0].data[1]],
    ['王五', chartData.series[0].data[2]],
    ['赵六', chartData.series[0].data[3]],
  ]);

  // 在 chart sheet 中插入图表
  const chart = echarts.init(document.createElement('canvas'), null, {
    
    
    devicePixelRatio: 2
  });
  const option = chartData;
  chart.setOption(option);
  const chartImage = new Image();
  chartImage.src = chart.getDataURL({
    
    
    type: 'png',
    pixelRatio: 2
  });
  XLSX.utils.sheet_add_image(chartSheet, chartImage, {
    
    
    tl: {
    
     col: 0, row: 6 },
    br: {
    
     col: 5, row: 18 }
  });

  // 添加 sheets 到 workbook
  XLSX.utils.book_append_sheet(workbook, sheet, '数据');
  XLSX.utils.book_append_sheet(workbook, chartSheet, '汇总');

  // 生成 Excel 文件
  const excelBuffer = XLSX.write(workbook, {
    
     bookType: 'xlsx', type: 'array' });
  const filePath = `${
      
      wx.env.USER_DATA_PATH}/${
      
      filename}.xlsx`;

  // 保存文件并分享
  wx.saveFile({
    
    
    tempFilePath: filePath,
    filePath: filePath,
    success: function(res) {
    
    
      const savedFilePath = res.savedFilePath;

      wx.shareFile({
    
    
        filePath: savedFilePath,
        success: function(res) {
    
    
          console.log('分享成功');
        },
        fail: function(error) {
    
    
          console.log('分享失败', error);
        }
      });
    },
    fail: function(error) {
    
    
      console.log('保存文件失败', error);
    }
  });
}

In the above example code, we exportExceladded some extra logic in the method to generate the chart data and insert the chart into the summary of the Excel file.

First, we created a chartSheetchart sheet named and used XLSX.utils.aoa_to_sheetthe method to convert the chart data into sheet data. Then, use echartsthe library to create a chart instance and set the chart's configuration items. Next, use chart.getDataURLthe method to convert the chart into a picture, and use XLSX.utils.sheet_add_imagethe method to insert the chart picture into the chart sheet.

Finally, we add the data sheet and chart sheet to the workbook, and XLSX.writewrite the workbook into an array through the method. Then, use wx.saveFilethe method to save the array to a local file, and wx.shareFilethe method to share the file.

Next, you can call exportExcelthe method to export the Excel report and share the file:

// 示例数据
const data = [
  ['姓名', '年龄', '性别'],
  ['张三', 25, '男'],
  ['李四', 30, '女'],
  ['王五', 28, '男']
];

// 调用导出 Excel 报表的方法
exportExcel(data, '报表');

In the above example, we defined an dataarray named which contains the data to be exported. Then, call exportExcelthe method to export the Excel report and specify the file name '报表'.

Please note that the above sample code is for reference only, and the specific implementation may need to be adjusted according to your actual needs.

Export to PDF

To convert the generated Excel file to PDF format, you can use third-party libraries xlsxand pdfmake. First, use xlsxto read the Excel file as data, then use to pdfmakeconvert the data to PDF format.

Here is a sample code that demonstrates how to convert the generated Excel file to PDF:

  1. First, install the dependent libraries xlsxand pdfmake, you can use npm to install:
npm install xlsx pdfmake
  1. xlsxIntroduce the and library into the applet page pdfmake, and define a method to convert Excel files to PDF:
// 引入依赖库
const XLSX = require('xlsx');
const pdfMake = require('pdfmake/build/pdfmake');
const pdfFonts = require('pdfmake/build/vfs_fonts');

// 注册字体
pdfMake.vfs = pdfFonts.pdfMake.vfs;

// 定义将 Excel 文件转换为 PDF 的方法
function convertToPDF(filePath, callback) {
    
    
  // 读取 Excel 文件
  const wb = XLSX.readFile(filePath);

  // 将 Excel 数据转换为 JSON 对象
  const sheetName = wb.SheetNames[0];
  const worksheet = wb.Sheets[sheetName];
  const jsonData = XLSX.utils.sheet_to_json(worksheet, {
    
     header: 1 });

  // 将 JSON 对象转换为 PDF
  const docDefinition = {
    
    
    content: [
      {
    
    
        table: {
    
    
          body: jsonData
        }
      }
    ]
  };

  const pdfDocGenerator = pdfMake.createPdf(docDefinition);
  pdfDocGenerator.getBlob((blob) => {
    
    
    if (typeof callback === 'function') {
    
    
      callback(blob);
    }
  });
}

In the above example code, we requireintroduced xlsxthe and pdfmakelibraries through the statement. Then, we registered the font files for use when generating PDFs.

Next, a method named is defined convertToPDF, which accepts a parameter filePathindicating the path of the Excel file to be converted. In the method, we xlsxread the Excel file as data using the method and XLSX.utils.sheet_to_jsonconvert the data into a JSON object using the method.

We then use pdfmaketo convert the JSON object to PDF. We create an docDefinitionobject whose contentproperties define the structure of the PDF content. In this example, we use a table to display Excel data.

Finally, we pdfMake.createPdfcreate a PDF document generator through the method, and use getBlobthe method to convert the generated PDF into a Blob object and return it through the callback function.

Next, you can use convertToPDFthe method to convert the generated Excel file to PDF and perform further operations, such as saving it locally or sharing it:

// 调用将 Excel 文件转换为 PDF 的方法
convertToPDF('path/to/excel.xlsx', (pdfBlob) => {
    
    
  // 在这里可以进行进一步的操作,比如保存到本地或分享
});

In the above example, we called convertToPDFthe method and passed in the path to the Excel file. In the callback function, you can perform further operations on the generated PDF Blob object, such as saving it locally or sharing it.

Please note that the above sample code is for reference only, and the specific implementation may need to be adjusted according to your actual needs. In addition, the mini program may have restrictions on file system operations and may not be able to directly save and share PDF files. You may need to make adjustments based on the actual situation.

Guess you like

Origin blog.csdn.net/gao511147456/article/details/132009965