Java实现更新excel文件内容

引入依赖

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.1</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.1</version>
</dependency>

代码实现

基本思路

首先获取到需要更新到excel中的数据集合,然后获取到需要更新的excel文件,最后更新到excel中后下载excel。


获取excel文件

// 获取文件根目录
String rootPath = System.getProperty("user.dir");
// 获取文件名称
String fileName = rootPath+"/files/Xbar-R控制图.xlsx";
// 读取Excel文档
File finalXlsxFile = new File(modelFile);

poi常用方法

  • Workbook

经常遇到的有通过上传文件MultipartFile与本地文件File来得到Workbook.

private static Workbook getWorkbook(MultipartFile mFile, File file) throws IOException {
    boolean fileNotExist = (file == null || !file.exists());
    if (mFile == null && fileNotExist) {
        return null;
    }
    // 解析表格数据
    InputStream in;
    String fileName;
    if (mFile != null) {
        // 上传文件解析
        in = mFile.getInputStream();
        fileName = getString(mFile.getOriginalFilename()).toLowerCase();
    } else {
        // 本地文件解析
        in = new FileInputStream(file);
        fileName = file.getName().toLowerCase();
    }
    Workbook book;
    if (fileName.endsWith(XLSX)) {
        book = new XSSFWorkbook(in);
    } else if (fileName.endsWith(XLS)) {
        POIFSFileSystem poifsFileSystem = new POIFSFileSystem(in);
        book = new HSSFWorkbook(poifsFileSystem);
    } else {
        return null;
    }
    in.close();
    return book;
}
  • Sheet

通过book.getSheetAt()来得到excel中的每一个sheet. 

for (int i = 0; i < book.getNumberOfSheets(); i++) {
    Sheet sheet = book.getSheetAt(i);
}
  • Row与Cell

常用方法如下

// 首行下标
int rowStart = sheet.getFirstRowNum();
// 尾行下标
int rowEnd = sheet.getLastRowNum();
// 获取表头行
Row headRow = sheet.getRow(rowStart);
// 获取第x行
Row dataRow = sheet.getRow(x-1);


// 表头首列下标
int cellStart = headRow.getFirstCellNum();
// 表头尾列下标
int cellEnd = headRow.getLastCellNum();
// 获取表头第y列
Cell headCell = headRow.getCell(y-1);
// 获取第x行第y列
Cell dataCell = sheet.getRow(x-1).getCell(y-1);


// cell赋值
dataCell.setCellValue(123);

excel更新时公式不能更新

// 重新计算公式
workBook.setForceFormulaRecalculation(true);

 完整示例

示例如下

public static void updateResExcelEx(List<List<List<Float>>> excelList,
                                    String modelFile, String exportName, String userAgent,
                                    HttpServletResponse res) {
    OutputStream out = null;
    try {
        // 读取Excel文档
        File finalXlsxFile = new File(modelFile);
        Workbook workBook = getWorkbok(null, finalXlsxFile);
        int i = 0;
        for (List<List<Float>> varList : excelList) {
            Sheet sheet = workBook.getSheetAt(i);
            // 业务代码省略
        }
        // 重新计算公式
        workBook.setForceFormulaRecalculation(true);
        res.setCharacterEncoding("UTF-8");
        res.setHeader("content-type", "application/octet-stream; charset=utf-8");

        String dname="";
        try {
            if(userAgent.contains("MSIE")||userAgent.contains("Trident")) {//针对IE或IE为内核的浏览器
                dname=java.net.URLEncoder.encode(exportName,"UTF-8");
            }else {
                dname=new String(exportName.getBytes("UTF-8"),"ISO-8859-1");//谷歌控制版本
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        res.setHeader("Content-Disposition", "attachment;filename="+dname+".xlsx");
        out = res.getOutputStream();

        workBook.write(out);
        System.out.println("数据导出成功");
    } catch (Exception e) {
        System.out.println("updateResExcelEx 异常");
        e.printStackTrace();
    } finally{
        try {
            if(out != null){
                out.flush();
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Java实现上传Excel文件,你可以使用一些常见的框架和库来简化该过程。下面是一个基本的示例代码,使用Spring Boot框架和Apache POI库来实现上传Excel文件: 1. 首先,确保在pom.xml文件中添加以下依赖: ```xml <!-- Spring Web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Apache POI --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <!-- 读取和写出xlsx文件需要的依赖 --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> ``` 2. 创建一个Controller类来处理上传请求: ```java import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; @RestController public class ExcelUploadController { @PostMapping("/upload") public ResponseEntity<String> uploadExcel(@RequestParam("file") MultipartFile file) { // 处理上传的Excel文件 try { // 使用Apache POI库解析Excel文件 Workbook workbook = WorkbookFactory.create(file.getInputStream()); // 对Excel文件进行处理,如读取数据或写入数据库等操作 return ResponseEntity.ok("Excel文件上传成功!"); } catch (Exception e) { e.printStackTrace(); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Excel文件上传失败!"); } } } ``` 3. 运行Spring Boot应用程序,并使用HTTP POST请求上传Excel文件: ``` POST /upload Content-Type: multipart/form-data Body: - file: [选择要上传的Excel文件] ``` 这是一个简单的示例,你可以根据自己的需求进行进一步的处理和操作。请确保在代码中处理异常情况,并根据实际需求进行适当的错误处理和返回。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值