java poi 操作excel,xssf 读excel 2007,将某些单元格为固定值

本来想看一下java IO,NIO,发现这块知识体系还挺大。暂时写一个操作excel的demo。由于时间关系,完成了功能,后期继续完善。

功能:读取excel表格(该表格为测试结果表格,共十几列,第一行是标题),,将第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的数据,把第一列标记为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 默认的第一个Row row = null;int totalRows = sheet.getLastRowNum(); // 总行数int totalCells = sheet.getRow(0).getLastCellNum();//总列数,根据第一行得来的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();}}

醒来第一眼看见的是他,然后倒头继续睡。这就是我想要的幸福。

java poi 操作excel,xssf 读excel 2007,将某些单元格为固定值

相关文章:

你感兴趣的文章:

标签云: