代码样例:JAVA+POI读写xlsx的Excel表格

该博客介绍了如何在Java中利用Apache POI库读取和写入Excel文件,并结合DeepL API进行文本翻译。示例代码展示了如何遍历Excel工作表,获取单元格内容,调用DeepL服务进行翻译并将结果存回Excel。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先是maven配置

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

接下来是代码样例

import org.apache.poi.ss.usermodel.Cell;
import org.testng.annotations.Test;
import pages.DeepLTransPage;
import org.apache.poi.xssf.usermodel.*;
import java.io.*;

public class TestCase_DeepLTrans {
    @Test
    public void testDeepLtrans() {
        try {
            DeepLTransPage deepl = new DeepLTransPage();
            String filePath = "D:\\pyws\\TextTranslation\\TextTranslation\\text.xlsx";
            FileInputStream intputStream = new FileInputStream(filePath);
            XSSFWorkbook  workbook = new XSSFWorkbook(intputStream);
            XSSFSheet  sheet;
            intputStream.close();
            sheet = workbook.getSheetAt(0);
            FileOutputStream out = new FileOutputStream(filePath);
            int rowNum = sheet.getLastRowNum();
            XSSFRow row = null;
            for (int r = 1; r <= rowNum; r++) {
                row = sheet.getRow(r);
                String v = row.getCell(1).toString();
                String dest = row.getCell(6).toString();
                if (dest.isEmpty()){
                    log.info("当前处理第 "+r+" 行");
                    log.info("原文为:"+ v);
                    String result = deepl.testDeepL(v);
                    XSSFCell cell= row.createCell(6,Cell.CELL_TYPE_STRING);
                    cell.setCellValue(result);
                }

            }
            out.flush();
            workbook.write(out);
            out.close();
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值