pom.xml添加依賴
<!-- office文檔組件 --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.9</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.9</version> </dependency> <dependency> <groupId>org.apache.xmlbeans</groupId> <artifactId>xmlbeans</artifactId> <version>2.4.0</version> </dependency>
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.junit.Test;
public class TestExcel {
// 讀取,全部sheet表及數據
@Test
public void showExcel() throws Exception {
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(new File("E:/temp/t1.xls")));
HSSFSheet sheet = null;
for (int i = 0; i < workbook.getNumberOfSheets(); i++) {// 獲取每個Sheet表
sheet = workbook.getSheetAt(i);
for (int j = 0; j < sheet.getLastRowNum() + 1; j++) {// getLastRowNum,獲取最后一行的行標
HSSFRow row = sheet.getRow(j);
if (row != null) {
for (int k = 0; k < row.getLastCellNum(); k++) {// getLastCellNum,是獲取最后一個不為空的列是第幾個
if (row.getCell(k) != null) { // getCell 獲取單元格數據
System.out.print(row.getCell(k) + "\t");
} else {
System.out.print("\t");
}
}
}
System.out.println(""); // 讀完一行后換行
}
System.out.println("讀取sheet表:" + workbook.getSheetName(i) + " 完成");
}
}
// 讀取,指定sheet表及數據
@Test
public void showExcel2() throws Exception {
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(new File("E:/temp/t1.xls")));
HSSFSheet sheet = null;
int i = workbook.getSheetIndex("xt"); // sheet表名
sheet = workbook.getSheetAt(i);
for (int j = 0; j < sheet.getLastRowNum() + 1; j++) {// getLastRowNum
// 獲取最后一行的行標
HSSFRow row = sheet.getRow(j);
if (row != null) {
for (int k = 0; k < row.getLastCellNum(); k++) {// getLastCellNum
// 是獲取最后一個不為空的列是第幾個
if (row.getCell(k) != null) { // getCell 獲取單元格數據
System.out.print(row.getCell(k) + "\t");
} else {
System.out.print("\t");
}
}
}
System.out.println("");
}
}
// 寫入,往指定sheet表的單元格
@Test
public void insertExcel3() throws Exception {
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(new File("E:/temp/t1.xls"))); // 讀取的文件
HSSFSheet sheet = null;
int i = workbook.getSheetIndex("xt"); // sheet表名
sheet = workbook.getSheetAt(i);
HSSFRow row = sheet.getRow(0); // 獲取指定的行對象,無數據則為空,需要創建
if (row == null) {
row = sheet.createRow(0); // 該行無數據,創建行對象
}
Cell cell = row.createCell(1); // 創建指定單元格對象。如本身有數據會替換掉
cell.setCellValue("tt"); // 設置內容
FileOutputStream fo = new FileOutputStream("E:/temp/t1.xls"); // 輸出到文件
workbook.write(fo);
}
}
問題:
1,excel某些單元格使用公式計算,如引用其他單元格的值,Java讀取不了需要經過計算后的值?
分析:原因是獲取有公式的單元格值前需要刷新公式,執行計算
解決:需要引用公式或保存excel(workbook.write(fo))前,添加:workbook.getCreationHelper().createFormulaEvaluator().evaluateAll();
