之前一直用jxl处理excel文件,但是jxl不能处理xlsx文件,局限性太大。最近开始尝试使用poi。
读取表格数据,或者创建新表格的教程如下:
http://www.yiibai.com/apache_poi/apache_poi_spreadsheets.html
实际运用中,有时需要在已有的Excel表格中写入数据。
具体代码如下:
Poi工具类如下:
package com.cmsz.crm.operation; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.*; /** * Util提供的所有静态方法返回的对象都是Workbook,可根据需求再做处理 * */ public class PoiUtil { public static final int Excel2003 = 2003; public static final int Excel2007 = 2007; /** * 根据版本号,获取Excel poi对象 * * @param edition * @param in * @return * @throws IOException */ public static Workbook getWorkbook(InputStream in, int edition) throws IOException { if (edition == Excel2003) { return new HSSFWorkbook(in); } else if (edition == Excel2007) { return new XSSFWorkbook(in); } return null; } /* * 判断excel文件是2003版的xml文件,还是xlsx文件 * @param inputFile * @return */ public static int getEdition(String inputFile){ int edition; String xlsxFile=inputFile.substring(inputFile.length()-4,inputFile.length()); String xlsFile=inputFile.substring(inputFile.length()-3,inputFile.length()); if( xlsxFile.equals("xlsx") ){ edition=Excel2007; }else if(xlsFile.equals("xls")) { edition=Excel2003; }else { edition=0; } return edition; } /** * 获取单元格的String值 * 文本型直接获取,数值型的一般是double类型,日期和数字要分开处理 * @param cell * @return */ public static String getCellString(Cell cell) { String cellStr=""; if(cell==null) { return cellStr; } switch (cell.getCellTypeEnum()) { case STRING: cellStr=cell.getStringCellValue(); if (cellStr.trim().isEmpty()) { cellStr = ""; } break; case NUMERIC: if( DateUtil.isCellDateFormatted(cell)) { Date date=cell.getDateCellValue(); cellStr=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date); }else { BigDecimal bigDecimal=new BigDecimal(cell.getNumericCellValue()); cellStr=bigDecimal.toString(); } break; case FORMULA: cellStr = new BigDecimal(cell.getNumericCellValue()).toPlainString(); break; case BLANK: cellStr = ""; break; default: break; } return cellStr; } /** * 从指定excel表格中逐行读取数据 * * @param workbook * @param startRow * @param startCol * @param indexSheet * @return */ public static List<List<String>> getExcelString(Workbook workbook, int startRow, int startCol, int indexSheet) { List<List<String>> stringTable = new ArrayList<List<String>>(); // 获取指定表对象 Sheet sheet = workbook.getSheetAt(indexSheet); // 获取最大行数 int rowNum = sheet.getLastRowNum(); for (int i = startRow; i <= rowNum; i++) { List<String> oneRow = new ArrayList<String>(); Row row = sheet.getRow(i); // 根据当前指针所在行数计算最大列数 int colNum = row.getLastCellNum(); for (int j = startCol; j <= colNum; j++) { // 确定当前单元格 Cell cell = row.getCell(j); String cellValue = null; if (cell != null) { // 验证每一个单元格的类型 switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: // 表格中返回的数字类型是科学计数法因此不能直接转换成字符串格式 cellValue = new BigDecimal(cell.getNumericCellValue()).toPlainString(); break; case Cell.CELL_TYPE_STRING: cellValue = cell.getStringCellValue(); break; case Cell.CELL_TYPE_FORMULA: cellValue = new BigDecimal(cell.getNumericCellValue()).toPlainString(); break; case Cell.CELL_TYPE_BLANK: cellValue = ""; break; case Cell.CELL_TYPE_BOOLEAN: cellValue = Boolean.toString(cell.getBooleanCellValue()); break; case Cell.CELL_TYPE_ERROR: cellValue = "ERROR"; break; default: cellValue = "UNDEFINE"; } } else { cellValue = ""; } // 生成一行数据 oneRow.add(cellValue); } stringTable.add(oneRow); } return stringTable; } /** * 根据给定的数据直接生成workbook * * @param workbook * @param sheetName * @param data * @return */ public static Workbook createExcel(Workbook workbook, String sheetName, List<List<String>> data) { Sheet sheet = workbook.createSheet(sheetName); for (int i = 0; i < data.size(); i++) { List<String> oneRow = data.get(i); Row row = sheet.createRow(i); for (int j = 0; j < oneRow.size(); j++) { Cell cell = row.createCell(j); cell.setCellValue(oneRow.get(j)); } } return workbook; } /** * 往指定的sheet表中插入数据,插入的方法是提供一组valueMap。int[]是2维数组代表需要插入的数据坐标,从0开始 * * @param workbook * @param sheetIndex * @param valueMap * @return */ public static Workbook insertExcel(Workbook workbook, int sheetIndex, Map<int[], String> valueMap) { Sheet sheet = workbook.getSheetAt(sheetIndex); Iterator<Map.Entry<int[], String>> it = valueMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry<int[], String> cellEntry = it.next(); int x = cellEntry.getKey()[0]; int y = cellEntry.getKey()[1]; String value = cellEntry.getValue(); Row row = sheet.getRow(y); Cell cell = row.getCell(x); cell.setCellValue(value); } return workbook; } /** * 删除指定行 * * @param workbook * @param sheetIndex * @param rowIndex * @return */ public static Workbook removeRow(Workbook workbook, int sheetIndex, int rowIndex) { Sheet sheet = workbook.getSheetAt(sheetIndex); int lastRowNum = sheet.getLastRowNum(); if (rowIndex >= 0 && rowIndex < lastRowNum) { sheet.shiftRows(rowIndex + 1, lastRowNum, -1); } if (rowIndex == lastRowNum) { sheet.removeRow(sheet.getRow(rowIndex)); } return workbook; } }
Excel读写的Demo如下:
package com.example.excel; import com.sun.org.apache.xpath.internal.SourceTree; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.*; import java.lang.reflect.Method; import java.math.BigDecimal; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.*; /** * Excel读写 * 文件:C:UserslenovoDesktopExcelTest.xlsx */ public class ExcelDemo { public static void main(String[] args) throws Exception { String input="C:\Users\lenovo\Desktop\ExcelTest.xlsx"; // writeExcel(input,2007); //xlsx格式用2007,xls格式用2003 readExcel(input,2007); } public static void readExcel(String file,int edition) throws Exception {//读取2003和2007版本的Excel try { //创建文件流 FileInputStream fis=new FileInputStream(new File(file)); //通过接口实例化Workbook工作簿 Workbook workbook=PoiUtil.getWorkbook(fis,edition); //通过接口获得默认的第一个sheet的页面 Sheet sheet = workbook.getSheetAt(0); //获取sheet页的第一行 Row row1 = sheet.getRow(0); //从第二行开始读,遍历到最后一行 for (int i = 1; i <= sheet.getLastRowNum(); i++) { Row row = sheet.getRow(i);//得到每一行 for (int j = 0; j < row.getLastCellNum(); j++) {//得到每一行的每一列 Cell cell = row.getCell(j); // 根据excel中单元格的属性,来用不同的格式取得有效值 String cellValue = PoiUtil.getCellString(cell); System.out.println("单元格内容为:"+cellValue); } } fis.close(); workbook.close(); } catch (Exception e) { e.printStackTrace(); } } public static void writeExcel(String file,int edition) throws Exception{ FileInputStream fis=new FileInputStream(new File(file)); Workbook workbook=PoiUtil.getWorkbook(fis,edition); Sheet sheet=workbook.getSheetAt(0); try { //获取第一行 Row row0=sheet.getRow(0); //在第一行第一列写入数据,类型为string Cell cell0=row0.createCell(0, CellType.STRING); cell0.setCellValue("Order"); //在第二行开始写入数据 for (int i = 1; i <= sheet.getLastRowNum(); i++) { Row row = sheet.getRow(i); Cell cell=row.createCell(0, CellType.STRING); cell.setCellValue( String.valueOf(i+1) ); } }catch (Exception e){ e.printStackTrace(); } fis.close(); //刷新流的缓存区,将数据写入excel FileOutputStream fos=new FileOutputStream(file); fos.flush(); workbook.write(fos); //关闭文件流 fos.close(); workbook.close(); } }
参考博客: