POI入门(以及两个实用工具类)

1、HelloPOI 在我们实际的开发中,常常有需要导入导出excel和word的要求,,POI便是一个很好的解决方案。 Apache的Jakata项目的POI子项目,目前比较成熟的是HSSF接口,处理MSExcel对象。它不象我们仅仅是用csv生成的没有格式的可以由Excel转换的东西,而是真正的Excel对象,你可以控制一些属性如sheet,cell等等。 首先,理解一下一个Excel的文件的组织形式,一个Excel文件对应于一个workbook(HSSFWorkbook),一个workbook可以有多个sheet(HSSFSheet)组成,一个sheet是由多个row(HSSFRow)组成,一个row是由多个cell(HSSFCell)组成。 HSSF是指Excel2007年以前的版本,XSSF是指Excel2007年版本以后的版本。 2、例子 POIExcelUtil.java

import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.text.DecimalFormat;import java.util.ArrayList;import java.util.Calendar;import java.util.List;import org.apache.poi.hssf.usermodel.HSSFCell;import org.apache.poi.hssf.usermodel.HSSFCellStyle;import org.apache.poi.hssf.usermodel.HSSFDataFormat;import org.apache.poi.hssf.usermodel.HSSFDateUtil;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.apache.poi.ss.usermodel.Row;import org.apache.poi.ss.usermodel.Sheet;import org.apache.poi.ss.usermodel.Workbook;{totalCells = 0;// 总列数private OutputStream out = null;private HSSFWorkbook workbook = null;private HSSFSheet sheet = null;String NUMBER_FORMAT = String DATE_FORMAT = () {}// 根据文件名读取excel文件public List<ArrayList<String>> read(String fileName, int sheetNo,int beginRowNo, int endRowNo) {List<ArrayList<String>> dataLst = new ArrayList<ArrayList<String>>();// 检查文件名是否为空或者是否是Excel格式的文件if (fileName == null || !fileName.matches(“^.+\\.(?i)((xls)|(xlsx))$”)) {return dataLst;}boolean isExcel2003 = true;// 对文件的合法性进行验if (fileName.matches(“^.+\\.(?i)(xlsx)$”)) {isExcel2003 = false;}// 检查文件是否存在File file = new File(fileName);if (file == null || !file.exists()) {return dataLst;}try {// 读取exceldataLst = read(new FileInputStream(file), isExcel2003, sheetNo,beginRowNo, endRowNo);} catch (Exception ex) {ex.printStackTrace();}return dataLst;}// 根据流读取Excel文件public List<ArrayList<String>> read(InputStream inputStream,boolean isExcel2003, int sheetNo, int beginRowNo, int endRowNo) {List<ArrayList<String>> dataLst = null;try {// 根据版本选择创建Workbook的方式Workbook wb = isExcel2003 ? new HSSFWorkbook(inputStream): new HSSFWorkbook(inputStream);dataLst = read(wb, sheetNo, beginRowNo, endRowNo);} catch (IOException e) {e.printStackTrace();}return dataLst;}() {return totalRows;}() {return totalCells;}// 读取数据private List<ArrayList<String>> read(Workbook wb, int sheetNo,int beginRowNo, int endRowNo) {List<ArrayList<String>> dataLst = new ArrayList<ArrayList<String>>();Sheet sheet = wb.getSheetAt(sheetNo – 1);// 得到第一个shellthis.totalRows = sheet.getPhysicalNumberOfRows();if (this.totalRows >= 1 && sheet.getRow(0) != null) {this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();}(int r = beginRowNo – 1; r < endRowNo; r++) {Row row = sheet.getRow(r);if (row == null) {continue;}ArrayList<String> rowLst = new ArrayList<String>();// 循环Excel的列for (short c = 0; c < this.getTotalCells(); c++) {Cell cell = row.getCell(c);String cellValue = “”;if (cell == null) {rowLst.add(cellValue);continue;}// 处理数字型的,自动去零if (Cell.CELL_TYPE_NUMERIC == cell.getCellType()) {// 在excel里,日期也是数字,在此要进行判断if (HSSFDateUtil.isCellDateFormatted(cell)) {cellValue = DateUtil.get4yMdHms(cell.getDateCellValue());} else {cellValue = getRightStr(cell.getNumericCellValue() + “”);}} else if (Cell.CELL_TYPE_STRING == cell.getCellType()) { // 处理字符串型cellValue = cell.getStringCellValue();} else if (Cell.CELL_TYPE_BOOLEAN == cell.getCellType()) { // 处理布尔型cellValue = cell.getBooleanCellValue() + “”;} else { // 其它数据类型cellValue = cell.toString() + “”;}rowLst.add(cellValue);}dataLst.add(rowLst);}return dataLst;}// 正确地处理整数后自动加零的情况private String getRightStr(String sNum) {DecimalFormat decimalFormat = new DecimalFormat(“#.000000”);String resultStr = decimalFormat.format(new Double(sNum));if (resultStr.matches(“^[-+]?\\d+\\.[0]+$”)) {resultStr = resultStr.substring(0, resultStr.indexOf(“.”));}return resultStr;}/*** 初始化write*/(OutputStream out) {this.out = out;this.workbook = new HSSFWorkbook();this.sheet = workbook.createSheet();}/*** 导出Excel文件* @throws Exception*/() throws Exception {try {workbook.write(out);out.flush();out.close();} catch (FileNotFoundException e) {throw new Exception(“生成导出Excel文件出错! “, e);} catch (IOException e) {throw new Exception(“写入Excel文件出错! “, e);}}/*** 增加一行* @param index 行号*/(int index) {this.row = this.sheet.createRow(index);}/*** 设置单元格* @param index 列号* @param value 单元格填充值*/(int index, int value) {HSSFCell cell = this.row.createCell(index);cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);cell.setCellValue(value);}/*** 设置单元格* @param index 列号* @param value 单元格填充值*/(int index, double value) {HSSFCell cell = this.row.createCell(index);cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);cell.setCellValue(value);HSSFCellStyle cellStyle = workbook.createCellStyle();// 建立新的cell样式HSSFDataFormat format = workbook.createDataFormat();cellStyle.setDataFormat(format.getFormat(NUMBER_FORMAT)); // 设置cell样式为定制的浮点数格式cell.setCellStyle(cellStyle);// 设置该cell浮点数的显示格式}/*** 设置单元格* @param index 列号* @param value 单元格填充值*/(int index, String value) {HSSFCell cell = this.row.createCell(index);cell.setCellType(HSSFCell.CELL_TYPE_STRING);cell.setCellValue(value);}/*** 设置单元格* @param index列号* @param value单元格填充值*/(int index, Calendar value) {HSSFCell cell = this.row.createCell(index);cell.setCellValue(value.getTime());HSSFCellStyle cellStyle = workbook.createCellStyle(); // 建立新的cell样式cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat(DATE_FORMAT)); // 设置cell样式为定制的日期格式cell.setCellStyle(cellStyle); // 设置该cell日期的显示格式}(String[] args) throws Exception {POIExcelUtil e = new POIExcelUtil();System.out.println(” 开始导出Excel文件 “);File f = new File(“d://哈喽.xlsx”);try {e.initWrite(new FileOutputStream(f));} catch (FileNotFoundException e1) {e1.printStackTrace();}e.createRow(0);e.setCell(0, “试题编码 “);e.setCell(1, “题型”);e.setCell(2, “分值”);e.setCell(3, “难度”);e.setCell(4, “级别”);e.setCell(5, “知识点”);for(int i=1;i<10;i++){e.createRow(i);e.setCell(0, “t”+i);e.setCell(1, 1+i);e.setCell(2, 3.0+i);e.setCell(3, 1+i);e.setCell(4, “重要”+i);e.setCell(5, “专业”+i);}try {e.export();System.out.println(” 导出Excel文件[成功] “);} catch (Exception ex) {System.out.println(” 导出Excel文件[失败] “);ex.printStackTrace();}}}你是自由的,不仅是身体上的自由,

POI入门(以及两个实用工具类)

相关文章:

你感兴趣的文章:

标签云: