赞
踩
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10.1</version>
</dependency>
//创建工作簿 Workbook workbook = new HSSFWorkbook(); //创建第一个表 Sheet sheet = workbook.createSheet("03版本"); //创建第一行 Row row1 = sheet.createRow(0); //创建第一个单元格(1,1) Cell cell11 = row1.createCell(0); //创建第一个单元格(1,2) Cell cell12 = row1.createCell(1); cell11.setCellValue("今日新增观众"); cell12.setCellValue("日期"); //创建第二行 Row row2 = sheet.createRow(1); //(2,1) Cell cell21 = row2.createCell(0); //(2,2) Cell cell22 = row2.createCell(1); cell21.setCellValue("李白"); cell22.setCellValue(new DateTime().toString("yyyy-MM-dd HH:mm:ss")); //后缀名一定要准确 03版xls FileOutputStream fileOutputStream = new FileOutputStream(PATH + "测试03.xls"); workbook.write(fileOutputStream); fileOutputStream.close(); System.out.println("输出Excel完毕");
//创建工作簿 Workbook workbook = new XSSFWorkbook(); //创建第一个表 Sheet sheet = workbook.createSheet("07版本"); //创建第一行 Row row1 = sheet.createRow(0); //创建第一个单元格(1,1) Cell cell11 = row1.createCell(0); //创建第一个单元格(1,2) Cell cell12 = row1.createCell(1); cell11.setCellValue("今日新增观众"); cell12.setCellValue("日期"); //创建第二行 Row row2 = sheet.createRow(1); //(2,1) Cell cell21 = row2.createCell(0); //(2,2) Cell cell22 = row2.createCell(1); cell21.setCellValue("杜甫"); cell22.setCellValue(new DateTime().toString("yyyy-MM-dd HH:mm:ss")); //后缀名一定要准确 07版xlsx FileOutputStream fileOutputStream = new FileOutputStream(PATH + "测试07.xlsx"); workbook.write(fileOutputStream); fileOutputStream.close(); System.out.println("输出Excel完毕");
long begin = System.currentTimeMillis();
Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet();
for (int i = 0; i < 65536; i++) {
Row row = sheet.createRow(i);
for (int j = 0; j < 10; j++) {
Cell cell = row.createCell(j);
cell.setCellValue(j);
}
}
FileOutputStream fileOutputStream = new FileOutputStream(PATH + "testWrite03BigData.xls");
workbook.write(fileOutputStream);
fileOutputStream.close();
long last = System.currentTimeMillis();
System.out.println((double) (last - begin) / 1000);
long begin = System.currentTimeMillis(); Workbook workbook = new SXSSFWorkbook(); Sheet sheet = workbook.createSheet(); for (int i = 0; i < 1000000; i++) { Row row = sheet.createRow(i); for (int j = 0; j < 10; j++) { Cell cell = row.createCell(j); cell.setCellValue(j); } } FileOutputStream fileOutputStream = new FileOutputStream(PATH + "testWrite07BigDataS.xlsx"); workbook.write(fileOutputStream); fileOutputStream.close(); //清除临时文件 ((SXSSFWorkbook) workbook).dispose(); long last = System.currentTimeMillis(); System.out.println((double) (last - begin) / 1000);
public static void readType() throws Exception { FileInputStream fileInputStream = new FileInputStream(PATH + "测试03.xls"); Workbook workbook = new HSSFWorkbook(fileInputStream); Sheet sheet = workbook.getSheet("03版本"); //获取第一行 Row rowTitle = sheet.getRow(0); if (rowTitle != null) { //获取一行总共多少单元格 int cellCount = rowTitle.getPhysicalNumberOfCells(); for (int cellNum = 0; cellNum < cellCount; cellNum++) { Cell cell = rowTitle.getCell(cellNum); if (cell != null) { int cellType = cell.getCellType(); String stringCellValue = cell.getStringCellValue(); System.out.print(stringCellValue + "|"); } } System.out.println(); } //获取一共多少行 int rowCount = sheet.getPhysicalNumberOfRows(); for (int rowNum = 1; rowNum < rowCount; rowNum++) { Row row = sheet.getRow(rowNum); if (row != null) { //读取列 int cellCount = rowTitle.getPhysicalNumberOfCells(); for (int cellNum = 0; cellNum < cellCount; cellNum++) { System.out.print("[" + (rowNum + 1) + "-" + (cellNum + 1) + "]"); Cell cell = row.getCell(cellNum); if (cell != null) { //类型判断 int cellType = cell.getCellType(); //接受返回值 String cellValue = ""; switch (cellType) { //字符串 case HSSFCell .CELL_TYPE_STRING: System.out.print("{String}"); cellValue = cell.getStringCellValue(); break; case HSSFCell.CELL_TYPE_BLANK: //空 System.out.print("{BLANK}"); break; case HSSFCell.CELL_TYPE_BOOLEAN: System.out.print("{BOOLEAN}"); cellValue = String.valueOf(cell.getBooleanCellValue()); break; case HSSFCell.CELL_TYPE_NUMERIC: //数字(日期 ,普通数字) System.out.print("{NUMERIC}"); if (HSSFDateUtil.isCellDateFormatted(cell)) { System.out.print("{日期}"); Date date = cell.getDateCellValue(); cellValue = new DateTime(date).toString("yyyy-MM-dd"); } else { //不是日期格式,防止数字过长 System.out.print("{转换为字符串输出}"); cell.setCellType(HSSFCell.CELL_TYPE_STRING); cellValue = cell.toString(); } break; case HSSFCell.CELL_TYPE_ERROR: System.out.print("{数据类型错误}"); break; } System.out.println(cellValue); } } } } fileInputStream.close(); }
见语雀
https://www.yuque.com/easyexcel/doc/read
导入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.3</version>
</dependency>
封装一个对象
@Data
public class DemoData {
@ExcelProperty("字符串标题")
private String string;
@ExcelProperty("日期标题")
private Date date;
@ExcelProperty("数字标题")
private Double doubleData;
/**
* 忽略这个字段
*/
@ExcelIgnore
private String ignore;
测试(还有其他方法,这里仅实验最简单的)
private static String PATH = "D:\\ideaDemo\\danli\\"; private static List<DemoData> data() { List<DemoData> list = new ArrayList<DemoData>(); for (int i = 0; i < 10; i++) { DemoData data = new DemoData(); data.setString("字符串" + i); data.setDate(new Date()); data.setDoubleData(0.56); list.add(data); } return list; } public static void simpleWrite() { // 写法1 // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭 // 如果这里想使用03 则 传入excelType参数即可 EasyExcel.write(PATH+"textEasyExcel.xls", DemoData.class).sheet("模板").doWrite(data()); }
public static void simpleRead() {
// 有个很重要的点 DemoDataListener 不能被spring管理,要每次读取excel都要new,然后里面用到spring可以构造方法传进去
// 写法1:
// 这里 需要指定读用哪个class去读,然后读取第一个sheet 文件流会自动关闭
EasyExcel.read(PATH+"textEasyExcel.xls", DemoData.class, new DemoDataListener()).sheet().doRead();
}
public class DemoDataListener extends AnalysisEventListener<DemoData> { private static final Logger LOGGER = LoggerFactory.getLogger(DemoDataListener.class); /** * 每隔5条存储数据库,实际使用中可以3000条,然后清理list ,方便内存回收 */ private static final int BATCH_COUNT = 5; List<DemoData> list = new ArrayList<DemoData>(); /** * 假设这个是一个DAO,当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。 */ private DemoDAO demoDAO; public DemoDataListener() { // 这里是demo,所以随便new一个。实际使用如果到了spring,请使用下面的有参构造函数 demoDAO = new DemoDAO(); } /** * 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来 * * @param demoDAO */ public DemoDataListener(DemoDAO demoDAO) { this.demoDAO = demoDAO; } /** * 这个每一条数据解析都会来调用 * * @param data * one row value. Is is same as {@link AnalysisContext#readRowHolder()} * @param context */ @Override public void invoke(DemoData data, AnalysisContext context) { LOGGER.info("解析到一条数据:{}", JSON.toJSONString(data)); list.add(data); // 达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOM if (list.size() >= BATCH_COUNT) { saveData(); // 存储完成清理 list list.clear(); } } /** * 所有数据解析完成了 都会来调用 * * @param context */ @Override public void doAfterAllAnalysed(AnalysisContext context) { // 这里也要保存数据,确保最后遗留的数据也存储到数据库 saveData(); LOGGER.info("所有数据解析完成!"); } /** * 加上存储数据库 */ private void saveData() { LOGGER.info("{}条数据,开始存储数据库!", list.size()); demoDAO.save(list); LOGGER.info("存储数据库成功!"); } }
public class DemoDAO {
public void save(List<DemoData> list) {
// 如果是mybatis,尽量别直接调用多次insert,自己写一个mapper里面新增一个方法batchInsert,所有数据一次性插入
System.out.println("存到数据库");
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。