首页 > 代码库 > POI操作excel
POI操作excel
1.导出一个excel文件,写入内容:
package poi;import org.apache.poi.hssf.usermodel.*;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.util.Date;/** */public class POICreateTest { public static void main(String args[]){ HSSFWorkbook wb=new HSSFWorkbook(); HSSFSheet sheet=wb.createSheet("new sheet"); HSSFRow row=sheet.createRow((short)0); HSSFCell cell=row.createCell((short)0); cell.setCellValue(1); row.createCell((short)1).setCellValue(1.2); row.createCell((short) 2).setCellValue("test"); row.createCell((short) 3).setCellValue(true); HSSFCellStyle cellStyle=wb.createCellStyle(); cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm")); HSSFCell dCell=row.createCell((short) 4); dCell.setCellValue(new Date()); dCell.setCellStyle(cellStyle); HSSFCell csCell=row.createCell((short) 5); csCell.setCellType(HSSFCell.ENCODING_UTF_16); csCell.setCellValue("你好啊——hello"); row.createCell((short) 6).setCellType(HSSFCell.CELL_TYPE_ERROR); try { FileOutputStream fileOut=new FileOutputStream("D:\\workbook.xls"); try { wb.write(fileOut); fileOut.close(); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } }}
2.导入一个excel,读取其中的内容:
package poi;import org.apache.poi.hssf.usermodel.HSSFCell;import org.apache.poi.hssf.usermodel.HSSFDateUtil;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 java.io.FileInputStream;import java.io.IOException;import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.Date;/** */public class POIReadTest { public static String file="D:\\workbook.xls"; public static void main(String args[]){ try { HSSFWorkbook workbook=new HSSFWorkbook(new FileInputStream(file)); HSSFSheet sheet=workbook.getSheetAt(0); //遍历行 for (Row row:sheet){ for(Cell cell:row){ System.out.print(formatPOI((HSSFCell) cell)+" "); } System.out.println(""); } } catch (IOException e) { e.printStackTrace(); } } public static String formatPOI(HSSFCell cell){ switch (cell.getCellType()){ case HSSFCell.CELL_TYPE_BOOLEAN: return String.valueOf(cell.getBooleanCellValue()); case HSSFCell.CELL_TYPE_ERROR: return "this data is error"; case HSSFCell.CELL_TYPE_NUMERIC: if (HSSFDateUtil.isCellDateFormatted(cell)){ Date date=cell.getDateCellValue(); DateFormat dateFormat=new SimpleDateFormat("m/d/yy h:mm"); return dateFormat.format(date).toString(); }else { return String.valueOf(cell.getNumericCellValue()); } case HSSFCell.CELL_TYPE_STRING: return cell.getStringCellValue(); default: return "bad errors!!!"; } }}
POI操作excel
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。