首先是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();
}
}
}