java poi 操作excel,xssf 讀excel 2007,將某些單元格為固定值
來源:程序員人生 發布時間:2015-05-28 09:10:57 閱讀次數:4385次
本來想看1下java IO,NIO,發現這塊知識體系還挺大。暫時寫1個操作excel的demo。由于時間關系,完成了功能,后期繼續完善。
功能:讀取excel表格(該表格為測試結果表格,共10幾列,第1行是標題),將第0列標記為id(遞增),第9列標記為結果(默許是PASS),第10列標記為姓名。
本可使用excel的拖拽功能,但由于excel中的內容和樣式常常需要修改,因此致使重復工作。暫寫這個小demo,期待完善后功能更詳實。
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.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;
/**
* Created by n on 2015/4/29.
*/
public class InsertInfoToExcel {
//該方法判斷excel版本
static Workbook openWorkbook(InputStream in, String filename) throws IOException {
Workbook wb = null;
if (filename.endsWith(".xlsx")) {
wb = new XSSFWorkbook(in);//Excel 2007
} else {
wb = (Workbook) new HSSFWorkbook(in);//Excel 2003
}
return wb;
}
//該方法處理excel的數據,把第1列標記為id(遞增),第9列標記為結果(默許是PASS),第10列標記為姓名
public static void setExcelData(String fileName) throws Exception {
InputStream in = new FileInputStream(fileName); //創建輸入流
Workbook wb = openWorkbook(in, fileName);// 獲得Excel文件對象
Sheet sheet = wb.getSheetAt(0);// 獲得文件的指定工作表m 默許的第1個Row row = null;
int totalRows = sheet.getLastRowNum(); // 總行數
int totalCells = sheet.getRow(0).getLastCellNum();//總列數,根據第1行得來的
System.out.println("列數:" + totalCells + " 行數:" + totalRows);
//順次獲得每行
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
XSSFRow row = (XSSFRow) sheet.getRow(i);// 獲得行對象
if (row == null) {// 如果為空,不處理
continue;
}
//將第0列的標記為id,遞增。遇到空的先不管,跳過
if (row.getCell(0) != null) {
Cell cellIndex = row.getCell(0);
System.out.print(cellIndex.getNumericCellValue());
cellIndex.setCellValue(i);
} else {
XSSFCell cellIndex = row.createCell(0);
cellIndex.setCellValue(i);
}
//將第9列標記為測試結果,遇到空的就標記為PASS,非空的不管。
if (row.getCell(9) == null) {
XSSFCell cellResult = row.createCell(9);
System.out.print(cellResult.getStringCellValue());
cellResult.setCellValue("PASS");
}
//將第10列的標記為測試人員的名字。不論是不是空都標記為名字。
if (row.getCell(10) != null) {
XSSFCell cellName = row.getCell(10);
// System.out.print(cellName.getStringCellValue());
cellName.setCellValue("aashen");
} else {
XSSFCell cellName = row.createCell(10);
cellName.setCellValue("aashen");
}
}
//寫入數據,關閉
OutputStream out = new FileOutputStream(fileName);
wb.write(out);
in.close();
out.close();
}
public static void main(String[] args) throws Exception {
// String fileName="E:"+ File.separator+"hello.txt";
String fileName = "E://hi.xlsx";
setExcelData(fileName);
// File f=new File(fileName);
// if(f.exists())
// System.out.println("new file successfully");
// Writer out =new FileWriter(f);
// String str="hello";
// out.write(str);
// out.close();
}
}
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈