java中将外部上传的.xlsx格式和.xls格式文件转换为docx格式文件,带文本框

1.所需依赖:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-scratchpad</artifactId>
    <version>4.1.2</version>
</dependency>

2.代码:xls转docx

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Iterator;

@RestController
public class XlsConversionController {
    @RequestMapping("/uploadXlsConvert")
    public ResponseEntity<byte[]> uploadXlsConvert(@RequestParam("file") MultipartFile uploadedFile) throws Exception {
        InputStream fileInputStream = uploadedFile.getInputStream();
        if (!uploadedFile.getOriginalFilename().endsWith(".xls")) {
            throw new IllegalArgumentException("请您上传.xls格式文件");
        }
        Workbook workbook = new HSSFWorkbook(fileInputStream);
        Sheet sheet = workbook.getSheetAt(0);

        // 2. 创建 Word 文档
        XWPFDocument document = new XWPFDocument();

        // 3. 创建 Word 表格,大小与 Excel 表格相同
        int numRows = sheet.getPhysicalNumberOfRows();
        int numCols = sheet.getRow(0).getPhysicalNumberOfCells();
        XWPFTable table = document.createTable(numRows, numCols);

        // 4. 从 Excel 中读取数据并插入到 Word 表格中
        Iterator<Row> rowIterator = sheet.iterator();
        int rowIndex = 0;
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            Iterator<Cell> cellIterator = row.iterator();
            int colIndex = 0;
            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
                XWPFTableCell tableCell = table.getRow(rowIndex).getCell(colIndex);
                XWPFParagraph paragraph = tableCell.addParagraph();
                XWPFRun run = paragraph.createRun();
                run.setText(cell.toString());
                colIndex++;
            }
            rowIndex++;
        }

        // 5. 将 Word 文档转换为 byte array (blob)
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        document.write(outputStream);
        byte[] wordBytes = outputStream.toByteArray();
        outputStream.close();

        // 6. 关闭 Excel 文件
        fileInputStream.close();

        // 7. Create HTTP headers
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", "output.docx");

        // 8. Return the Word document as a ResponseEntity
        return ResponseEntity.ok()
                .headers(headers)
                .body(wordBytes);

    }
}

3.代码:xls转docx

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Iterator;

@RestController
public class XlsxConversionController {
    @RequestMapping("/uploadXlsxConvert")
    public ResponseEntity<byte[]> uploadXlsxConvert(@RequestParam("file") MultipartFile uploadedFile) throws Exception {
        InputStream fileInputStream = uploadedFile.getInputStream();
        if (!uploadedFile.getOriginalFilename().endsWith(".xlsx")) {
            throw new IllegalArgumentException("请您上传.xlsx格式文件");
        }
        Workbook workbook = new XSSFWorkbook(fileInputStream);
        Sheet sheet = workbook.getSheetAt(0);

        // 2. 创建 Word 文档
        XWPFDocument document = new XWPFDocument();

        // 3. 创建 Word 表格,大小与 Excel 表格相同
        int numRows = sheet.getPhysicalNumberOfRows();
        int numCols = sheet.getRow(0).getPhysicalNumberOfCells();
        XWPFTable table = document.createTable(numRows, numCols);

        // 4. 从 Excel 中读取数据并插入到 Word 表格中
        Iterator<Row> rowIterator = sheet.iterator();
        int rowIndex = 0;
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            Iterator<Cell> cellIterator = row.iterator();
            int colIndex = 0;
            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
                XWPFTableCell tableCell = table.getRow(rowIndex).getCell(colIndex);
                XWPFParagraph paragraph = tableCell.addParagraph();
                XWPFRun run = paragraph.createRun();
                run.setText(cell.toString());
                colIndex++;
            }
            rowIndex++;
        }

        // 5. 将 Word 文档转换为 byte array (blob)
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        document.write(outputStream);
        byte[] wordBytes = outputStream.toByteArray();
        outputStream.close();

        // 6. 关闭 Excel 文件
        fileInputStream.close();

        // 7. Create HTTP headers
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", "output.docx");

        // 8. Return the Word document as a ResponseEntity
        return ResponseEntity.ok()
                .headers(headers)
                .body(wordBytes);

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
你可以使用Apache POI库来解析Excel文件。下面是一个使用Java解析Excel文件的示例代码: ```java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook; public class ExcelParser { public static void main(String[] args) { String filePath = "path/to/your/excel/file.xlsx"; // 替换为你的Excel文件路径 try { FileInputStream fis = new FileInputStream(new File(filePath)); Workbook workbook; if (filePath.endsWith(".xlsx")) { workbook = new XSSFWorkbook(fis); // 处理.xlsx文件 } else if (filePath.endsWith(".xls")) { workbook = new HSSFWorkbook(fis); // 处理.xls文件 } else { throw new IllegalArgumentException("The specified file is not Excel file"); } Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表 for (Row row : sheet) { for (Cell cell : row) { CellType cellType = cell.getCellType(); if (cellType == CellType.STRING) { System.out.print(cell.getStringCellValue() + " "); } else if (cellType == CellType.NUMERIC) { System.out.print(cell.getNumericCellValue() + " "); } else if (cellType == CellType.BOOLEAN) { System.out.print(cell.getBooleanCellValue() + " "); } } System.out.println(); } workbook.close(); fis.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 请将代码的`"path/to/your/excel/file.xlsx"`替换为你实际的Excel文件路径。该代码会打开Excel文件并输出每个单元格的值。你可以根据需要对解析的内容进行进一步处理。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值