java实现docx文档下载

前端代码

本次开发前端用的是element-admin

<el-link :href= "downloadUrl">下载</el-link>


data() {
      return {
        downloadUrl: process.env.VUE_APP_BASE_API + '/facilitator/downloadAppConfig',

后端代码

1.本地下载

    @GetMapping("/downloadAppConfig")
    public void getQrConfig(HttpServletResponse response) throws IOException {
        File file = new File("F:\\123.docx");
        String fileName = file.getName();

        //设置文件ContentType类型,这样设置,会自动判断下载文件类型
        response.setContentType("multipart/form-data");
        //设置文件头:最后一个参数是设置下载文件名(假如我们叫a.pdf)
        response.setHeader("Content-Disposition", "attachment;fileName=" +
                new String(fileName.getBytes("utf-8"), "ISO-8859-1"));
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            byte[] b = new byte[bis.available() + 1000];
            int i = 0;
            os = response.getOutputStream();  //直接下载导出
            while ((i = bis.read(b)) != -1) {
                os.write(b, 0, i);
            }
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

2.七牛云路径下载

    @ApiOperation("下载公众号配置说明文件")
    @GetMapping("/downloadAppConfig")
    public void getQrConfig(HttpServletResponse response) throws IOException {
        // 密钥配置
        Auth auth = Auth.create(qiniuConfig.getACCESS_KEY(), qiniuConfig.getSECRET_KEY());
        String downloadUrl =  auth.privateDownloadUrl("http://**.**.**/**.docx");
        OkHttpClient client = new OkHttpClient();
        Request req = new Request.Builder().url(downloadUrl).build();
        Response resp = client.newCall(req).execute();
        if(resp.isSuccessful()) {
            ResponseBody body = resp.body();
            InputStream is = body.byteStream();
            String fileName = "123.docx";
            //设置文件头:最后一个参数是设置下载文件名(假如我们叫a.pdf)
            response.setHeader("Content-Disposition", "attachment;fileName=" +
                    new String(fileName.getBytes("utf-8"), "ISO-8859-1"));
            byte[] b = new byte[is.available() + 1000];
            int i = 0;
            ServletOutputStream sos = response.getOutputStream();  //直接下载导出
            while ((i = is.read(b)) != -1) {
                sos.write(b, 0, i);
            }
            sos.flush();
            sos.close();
        }
    }

依赖

        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.8.0</version>
        </dependency>
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用 Java 实现 Docx 文档模板对表格数据填充的步骤如下: 1. 首先,需要准备好一个 Docx 文档模板,其中包含需要填充数据的表格。 2. 使用 Apache POI 库打开 Docx 文档模板,并读取需要填充数据的表格。 3. 将需要填充的数据保存在 Java 对象中,例如 List<Map<String, String>>,其中每个 Map 对象表示一行表格数据,Map 的 key 表示表格列名,value 表示对应列的数据。 4. 遍历需要填充的数据,逐行对表格进行填充。 5. 在填充表格数据时,需要注意表格中可能存在合并单元格的情况,需要根据合并单元格的信息将数据正确地填充到表格中。 6. 填充完数据后,将修改后的文档保存到磁盘中。 下面是一个简单的示例代码,演示了如何使用 Java 实现 Docx 文档模板对表格数据填充: ``` import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.List; import java.util.Map; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFTable; import org.apache.poi.xwpf.usermodel.XWPFTableRow; import org.apache.poi.xwpf.usermodel.XWPFTableCell; public class DocxTemplateFiller { public static void fillTableData(String templatePath, String outputPath, List<Map<String, String>> data) throws Exception { // 打开文档模板 XWPFDocument doc = new XWPFDocument(new FileInputStream(templatePath)); // 获取需要填充数据的表格 XWPFTable table = doc.getTables().get(0); // 遍历数据,逐行填充表格 for (Map<String, String> row : data) { XWPFTableRow tableRow = table.createRow(); int colIndex = 0; for (Map.Entry<String, String> entry : row.entrySet()) { // 根据列名获取列索引 int rowIndex = getRowIndex(table, 0, entry.getKey(), colIndex); XWPFTableCell cell = tableRow.getCell(rowIndex); // 填充单元格数据 cell.setText(entry.getValue()); // 处理合并单元格 int[] mergeRange = getMergeRange(table, rowIndex, table.getNumberOfRows() - 1); if (mergeRange != null) { mergeCellsVertically(table, rowIndex, mergeRange[1], mergeRange[0]); colIndex = mergeRange[1] + 1; } else { colIndex = rowIndex + 1; } } } // 保存修改后的文档 doc.write(new FileOutputStream(outputPath)); doc.close(); } private static int getRowIndex(XWPFTable table, int rowStartIndex, String colName, int colStartIndex) { for (int rowIndex = rowStartIndex; rowIndex < table.getNumberOfRows(); rowIndex++) { XWPFTableRow row = table.getRow(rowIndex); for (int colIndex = colStartIndex; colIndex < row.getTableCells().size(); colIndex++) { String cellText = row.getCell(colIndex).getText(); if (cellText.contains(colName)) { return colIndex; } } } return -1; } private static int[] getMergeRange(XWPFTable table, int rowIndex, int rowEndIndex) { int[] range = null; for (int i = rowIndex; i <= rowEndIndex; i++) { XWPFTableRow row = table.getRow(i); XWPFTableCell cell = row.getCell(rowIndex); if (cell != null && cell.getCTTc().isSetTcPr()) { if (cell.getCTTc().getTcPr().isSetVMerge()) { int vMergeVal = cell.getCTTc().getTcPr().getVMerge().getVal(); if (vMergeVal == 0) { range = new int[]{rowIndex, i}; break; } } } } return range; } private static void mergeCellsVertically(XWPFTable table, int colIndex, int fromRow, int toRow) { for (int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) { XWPFTableRow row = table.getRow(rowIndex); XWPFTableCell cell = row.getCell(colIndex); if (rowIndex == fromRow) { cell.getCTTc().addNewTcPr().addNewVMerge().setVal(org.apache.poi.xwpf.usermodel.STMerge.CONTINUE); } else { row.getCell(colIndex).getCTTc().addNewTcPr().addNewVMerge(); } } } } ``` 这个示例代码中,fillTableData 方法接收三个参数:文档模板路径、输出路径和需要填充的数据。在方法中,首先打开文档模板,然后获取需要填充数据的表格。接着,遍历数据,逐行填充表格。 在填充表格数据时,使用 getRowIndex 方法根据列名获取列索引,然后根据索引获取单元格,再填充单元格数据。如果单元格属于一个合并单元格,使用 getMergeRange 方法获取合并单元格的范围,并使用 mergeCellsVertically 方法将数据填充到合并单元格中。 最后,将修改后的文档保存到磁盘中。注意,在保存文档之前,需要先关闭文档对象。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值