当前位置:   article > 正文

Java使用POI导出Excel_java poi导出excel

java poi导出excel

 

 

  1. <dependency>
  2. <groupId>org.apache.poi</groupId>
  3. <artifactId>poi-ooxml</artifactId>
  4. <version>4.1.2</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>cn.hutool</groupId>
  8. <artifactId>hutool-all</artifactId>
  9. <version>5.8.8</version>
  10. </dependency>

  1. import cn.hutool.core.date.DateUtil;
  2. import cn.hutool.core.io.FileUtil;
  3. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  4. import org.apache.poi.ss.usermodel.Cell;
  5. import org.apache.poi.ss.usermodel.Row;
  6. import org.apache.poi.ss.usermodel.Sheet;
  7. import org.apache.poi.ss.usermodel.Workbook;
  8. import java.io.File;
  9. import java.io.FileOutputStream;
  10. import java.io.IOException;
  11. public class ExcelWriterTest03 {
  12. public static void main(String[] args) throws IOException {
  13. String path = "D:\\poi\\";
  14. // 1.创建一个工作簿。03
  15. Workbook workbook = new HSSFWorkbook();
  16. // 2.创建一个工作表
  17. Sheet sheet = workbook.createSheet("统计表");
  18. // 3.创建行。第一行
  19. Row row = sheet.createRow(0);
  20. // 4.创建列。
  21. // (1,1) 第一行第一列的单元格
  22. Cell cell = row.createCell(0);
  23. cell.setCellValue("我们都一样");
  24. // (1,2) 第一行第二列的单元格
  25. Cell cell2 = row.createCell(1);
  26. cell2.setCellValue(666);
  27. // 第二行。(1,0)
  28. Row row1 = sheet.createRow(1);
  29. //(2,1)第二行第一列的单元格
  30. Cell cell1 = row1.createCell(0);
  31. cell1.setCellValue(DateUtil.now());
  32. // 判断文件是否存在,不存在就创建
  33. if (FileUtil.isEmpty(new File(path))) {
  34. FileUtil.mkdir(path);
  35. }
  36. // 5.生成一张表。03版本的工作簿是以.xls结尾
  37. FileOutputStream fileOutputStream = new FileOutputStream(path + "03.xls");
  38. // 输出
  39. workbook.write(fileOutputStream);
  40. // 6.关闭流
  41. fileOutputStream.close();
  42. System.out.println("03表生成成功!");
  43. }
  44. }

 

  1. import cn.hutool.core.date.DateUtil;
  2. import cn.hutool.core.io.FileUtil;
  3. import org.apache.poi.ss.usermodel.Cell;
  4. import org.apache.poi.ss.usermodel.Row;
  5. import org.apache.poi.ss.usermodel.Sheet;
  6. import org.apache.poi.ss.usermodel.Workbook;
  7. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  8. import java.io.File;
  9. import java.io.FileOutputStream;
  10. import java.io.IOException;
  11. public class ExcelWriterTest03 {
  12. public static void main(String[] args) throws IOException {
  13. String path = "D:\\poi\\";
  14. // 1.创建一个工作簿。03
  15. Workbook workbook = new XSSFWorkbook(); // 07和03版本只有对象不同,其他操作一样
  16. // 2.创建一个工作表
  17. Sheet sheet = workbook.createSheet("统计表");
  18. // 3.创建行。第一行
  19. Row row = sheet.createRow(0);
  20. // 4.创建列。
  21. // (1,1) 第一行第一列的单元格
  22. Cell cell = row.createCell(0);
  23. cell.setCellValue("我们都一样");
  24. // (1,2) 第一行第二列的单元格
  25. Cell cell2 = row.createCell(1);
  26. cell2.setCellValue(666);
  27. // 第65537行。(65537,0)
  28. Row row1 = sheet.createRow(65536);
  29. //(2,1)第二行第一列的单元格
  30. Cell cell1 = row1.createCell(0);
  31. cell1.setCellValue(DateUtil.now());
  32. // 判断文件是否存在,不存在就创建
  33. if (FileUtil.isEmpty(new File(path))) {
  34. FileUtil.mkdir(path);
  35. }
  36. // 5.生成一张表。03版本的工作簿是以.xls结尾
  37. FileOutputStream fileOutputStream = new FileOutputStream(path + "03.xls");
  38. // 输出
  39. workbook.write(fileOutputStream);
  40. // 6.关闭流
  41. fileOutputStream.close();
  42. System.out.println("03表生成成功!");
  43. }
  44. }

 

  1. public class ExcelWriterTest03BigData {
  2. public static void main(String[] args) throws IOException {
  3. // 开始时间
  4. long start = System.currentTimeMillis();
  5. String path = "D:\\poi\\";
  6. // 1.创建一个工作簿。03
  7. Workbook workbook = new SXSSFWorkbook(5000);
  8. // 2.创建一个工作表
  9. Sheet sheet = workbook.createSheet("统计表");
  10. // 3.创建行。
  11. for (int rowNum = 0; rowNum < 65537; rowNum++) {
  12. Row row = sheet.createRow(rowNum);
  13. for (int cellNum = 0; cellNum < 10; cellNum++) {
  14. Cell cell = row.createCell(cellNum);
  15. cell.setCellValue(rowNum + "," + cellNum);
  16. }
  17. }
  18. // 5.生成一张表。03版本的工作簿是以.xlsx结尾
  19. FileOutputStream fileOutputStream = new FileOutputStream(path + "07BigDataUpGrade.xlsx");
  20. // 输出
  21. workbook.write(fileOutputStream);
  22. // 6.关闭流
  23. fileOutputStream.close();
  24. // 7.清除临时文件
  25. ((SXSSFWorkbook) workbook).dispose();
  26. System.out.println("07大数据量表优化后生成成功!");
  27. // 结束时间
  28. long end = System.currentTimeMillis();
  29. System.out.println("用时:" + ((end - start) / 1000) + "秒");
  30. }
  31. }

 

  1. @Component
  2. public class ExcelConfig {
  3. private final static Logger logger = LoggerFactory.getLogger(ExcelConfig.class);
  4. @Value("${application.tmp.path}")
  5. private String applicationTmpPath;
  6. /**
  7. * 设置使用SXSSFWorkbook对象导出excel报表时,TempFile使用的临时目录,代替{java.io.tmpdir}
  8. */
  9. @PostConstruct
  10. public void setExcelSXSSFWorkbookTmpPath() {
  11. String excelSXSSFWorkbookTmpPath = applicationTmpPath + "/poifiles";
  12. File dir = new File(excelSXSSFWorkbookTmpPath);
  13. if (!dir.exists()) {
  14. dir.mkdirs();
  15. }
  16. TempFile.setTempFileCreationStrategy(new TempFile.DefaultTempFileCreationStrategy(dir));
  17. logger.info("setExcelSXSSFWorkbookTmpPath={}", excelSXSSFWorkbookTmpPath);
  18. }
  19. }

  1. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  2. import org.apache.poi.ss.usermodel.Cell;
  3. import org.apache.poi.ss.usermodel.Row;
  4. import org.apache.poi.ss.usermodel.Sheet;
  5. import org.apache.poi.ss.usermodel.Workbook;
  6. import java.io.FileOutputStream;
  7. import java.io.IOException;
  8. public class ExcelWriterTest03BigData {
  9. public static void main(String[] args) throws IOException {
  10. // 开始时间
  11. long start = System.currentTimeMillis();
  12. String path = "D:\\poi\\";
  13. // 1.创建一个工作簿。03
  14. Workbook workbook = new HSSFWorkbook();
  15. // 2.创建一个工作表
  16. Sheet sheet = workbook.createSheet("统计表");
  17. // 3.创建行。
  18. for (int rowNum = 0; rowNum < 65536; rowNum++) {
  19. Row row = sheet.createRow(rowNum);
  20. for (int cellNum = 0; cellNum < 10; cellNum++) {
  21. Cell cell = row.createCell(cellNum);
  22. cell.setCellValue(rowNum+","+cellNum);
  23. }
  24. }
  25. // 5.生成一张表。03版本的工作簿是以.xls结尾
  26. FileOutputStream fileOutputStream = new FileOutputStream(path + "03BigData.xls");
  27. // 输出
  28. workbook.write(fileOutputStream);
  29. // 6.关闭流
  30. fileOutputStream.close();
  31. System.out.println("03大数据量表生成成功!");
  32. // 结束时间
  33. long end = System.currentTimeMillis();
  34. System.out.println("用时:"+((end-start)/1000)+"秒");
  35. }
  36. }

 

  1. import org.apache.poi.ss.usermodel.Cell;
  2. import org.apache.poi.ss.usermodel.Row;
  3. import org.apache.poi.ss.usermodel.Sheet;
  4. import org.apache.poi.ss.util.CellReference;
  5. import org.apache.poi.xssf.streaming.SXSSFSheet;
  6. import org.apache.poi.xssf.streaming.SXSSFWorkbook;
  7. import java.io.FileOutputStream;
  8. import java.io.IOException;
  9. public class ClassSXSSFWorkBookUtil {
  10. public static void main(String[] args) throws IOException {
  11. long curr_time = System.currentTimeMillis();
  12. // 内存中缓存记录行数
  13. int rowAccess = 100;
  14. SXSSFWorkbook wb = new SXSSFWorkbook(rowAccess);
  15. // 生成3个SHEET
  16. int sheetNum = 3;
  17. for (int i = 0; i < sheetNum; i++) {
  18. Sheet sh = wb.createSheet();
  19. // 每一个SHEET有 200000 ROW
  20. for (int rowNum = 0; rowNum < 200000; rowNum++) {
  21. Row row = sh.createRow(rowNum);
  22. //每行有10个CELL
  23. for (int cellnum = 0; cellnum < 10; cellnum++) {
  24. Cell cell = row.createCell(cellnum);
  25. String address = new CellReference(cell).formatAsString();
  26. cell.setCellValue(address);
  27. }
  28. // 每当行数达到设置的值就刷新数据到硬盘,以清理内存,这块本质上其实不加这个poi在达到阀值也会向临时文件写数据,
  29. // 假如导出60w数据3个sheet,加上手动刷新是34s,然后不加是40s,所以在一定程度上来讲手动刷新要快一点
  30. if (rowNum % rowAccess == 0) {
  31. ((SXSSFSheet) sh).flushRows();
  32. }
  33. }
  34. }
  35. FileOutputStream os = new FileOutputStream("D:\\poi\\biggrid.xlsx");
  36. wb.write(os);
  37. os.close();
  38. System.out.println("耗时(秒):" + (System.currentTimeMillis() - curr_time) / 1000);
  39. }
  40. }

  1. import org.apache.poi.hssf.usermodel.*;
  2. import org.apache.poi.ss.usermodel.*;
  3. import org.apache.poi.ss.util.CellRangeAddress;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. public class Test {
  7. public static void main(String[] args) throws IOException {
  8. //创建HSSFWorkbook对象
  9. HSSFWorkbook wb = new HSSFWorkbook();
  10. //建立sheet对象
  11. HSSFSheet sheet = wb.createSheet("成绩表");
  12. // 设置列宽
  13. sheet.setColumnWidth(0, 25 * 256);
  14. sheet.setColumnWidth(1, 25 * 256);
  15. sheet.setColumnWidth(2, 25 * 256);
  16. sheet.setColumnWidth(3, 25 * 256);
  17. sheet.setColumnWidth(4, 25 * 256);
  18. // 记住一点设置单元格样式相关的都是CellStyle来控制的,设置完之后只需set给单元格即可:cell.setCellStyle(cellStyle);
  19. // 合并单元格后居中
  20. CellStyle cellStyle = wb.createCellStyle();
  21. // 垂直居中
  22. cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
  23. cellStyle.setAlignment(HorizontalAlignment.CENTER);
  24. // 设置字体
  25. Font font = wb.createFont();
  26. font.setFontName("宋体");
  27. font.setFontHeightInPoints((short) 16);
  28. font.setItalic(false);
  29. font.setStrikeout(false);
  30. cellStyle.setFont(font);
  31. // 设置背景色
  32. cellStyle.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex());
  33. cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  34. // 设置边框(一般标题不设置边框,是标题下的所有表格设置边框)
  35. cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
  36. cellStyle.setBorderLeft(BorderStyle.THIN);//左边框
  37. cellStyle.setBorderTop(BorderStyle.THIN);//上边框
  38. cellStyle.setBorderRight(BorderStyle.THIN);//右边框
  39. //在sheet里创建第一行,参数为行索引
  40. HSSFRow row1 = sheet.createRow(0);
  41. // 合并单元格:参数1:行号 参数2:起始列号 参数3:行号 参数4:终止列号
  42. sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 4));
  43. // 创建单元格
  44. HSSFCell cell = row1.createCell(0);
  45. cell.setCellStyle(cellStyle);
  46. //设置单元格内容
  47. cell.setCellValue("学生成绩表");
  48. //在sheet里创建第二行
  49. HSSFRow row2 = sheet.createRow(1);
  50. //创建单元格并设置单元格内容
  51. row2.createCell(0).setCellValue("姓名");
  52. row2.createCell(1).setCellValue("班级");
  53. row2.createCell(2).setCellValue("语文成绩");
  54. row2.createCell(3).setCellValue("数学成绩");
  55. row2.createCell(4).setCellValue("英语成绩");
  56. //在sheet里创建第三行
  57. HSSFRow row3 = sheet.createRow(2);
  58. row3.createCell(0).setCellValue("小明");
  59. row3.createCell(1).setCellValue("1班");
  60. row3.createCell(2).setCellValue(80);
  61. row3.createCell(3).setCellValue(75);
  62. row3.createCell(4).setCellValue(88);
  63. //在sheet里创建第四行
  64. HSSFRow row4 = sheet.createRow(3);
  65. row4.createCell(0).setCellValue("小红");
  66. row4.createCell(1).setCellValue("1班");
  67. row4.createCell(2).setCellValue(82);
  68. row4.createCell(3).setCellValue(70);
  69. row4.createCell(4).setCellValue(90);
  70. FileOutputStream fileOutputStream = new FileOutputStream("D:\\poi\\04.xlsx");
  71. wb.write(fileOutputStream);
  72. fileOutputStream.close();
  73. }
  74. }

  1. import org.apache.poi.ss.usermodel.Cell;
  2. import org.apache.poi.ss.usermodel.Row;
  3. import org.apache.poi.ss.usermodel.Sheet;
  4. import org.apache.poi.ss.usermodel.Workbook;
  5. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  6. import java.io.FileInputStream;
  7. import java.io.IOException;
  8. public class ExcelReadTest03 {
  9. public static void main(String[] args) throws IOException {
  10. String path = "D:\\poi\\";
  11. FileInputStream fileInputStream = new FileInputStream(path + "03.xlsx");
  12. // 1.创建一个工作簿。使得excel能操作的,这边他也能操作。
  13. // Workbook workbook = new HSSFWorkbook(fileInputStream);
  14. Workbook workbook = new XSSFWorkbook(fileInputStream);
  15. // 2.得到表。
  16. Sheet sheet = workbook.getSheetAt(0);
  17. // 3.得到行。
  18. Row row = sheet.getRow(0);
  19. // 4.得到列。
  20. Cell cell = row.getCell(0);
  21. // 读取值。一定要注意类型,否则会读取失败
  22. System.out.println(cell.getStringCellValue());// 字符串类型
  23. Cell cell1 = row.getCell(1);
  24. System.out.println(cell1.getNumericCellValue());// 数字类型
  25. // 5.关闭流。
  26. fileInputStream.close();
  27. }
  28. }

  1. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  2. import org.apache.poi.ss.usermodel.*;
  3. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  4. import java.io.FileInputStream;
  5. import java.io.IOException;
  6. import java.math.BigDecimal;
  7. import java.text.SimpleDateFormat;
  8. import java.util.Date;
  9. public class ExcelReadTestType {
  10. public static void main(String[] args) throws IOException {
  11. String path = "D:\\poi\\";
  12. // 1.获取文件流
  13. FileInputStream fileInputStream = new FileInputStream(path + "会员消费商品明细表.xls");
  14. // 2.创建一个工作簿。使用excel能操作的这边他也可以操作。
  15. Workbook workbook = new HSSFWorkbook(fileInputStream);
  16. // Workbook workbook = new XSSFWorkbook(fileInputStream);
  17. // 3.获取第一张表。
  18. Sheet sheet = workbook.getSheetAt(0);
  19. // 4.获取标题内容。
  20. Row rowTitle = sheet.getRow(0);
  21. if (rowTitle != null) {
  22. // 获取一行有多少列
  23. int cellCount = rowTitle.getPhysicalNumberOfCells();
  24. // 循环遍历,获取每一个标题名称
  25. for (int cellNum = 0; cellNum < cellCount; cellNum++) {
  26. Cell cell = rowTitle.getCell(cellNum);
  27. if (cell != null) {
  28. System.out.print(cell.getStringCellValue() + "|");
  29. }
  30. }
  31. System.out.println();
  32. }
  33. // 5.获取表中的记录
  34. // 获取有多少行记录
  35. int rowCount = sheet.getPhysicalNumberOfRows();
  36. for (int rowNum = 1; rowNum < rowCount; rowNum++) {
  37. // 获取每一行记录
  38. Row rowData = sheet.getRow(rowNum);
  39. if (rowData != null) {
  40. // 读取列
  41. int cellCount = rowTitle.getPhysicalNumberOfCells();
  42. for (int cellNum = 0; cellNum < cellCount; cellNum++) {
  43. // 获得单元格
  44. Cell cell = rowData.getCell(cellNum);
  45. // 匹配列的数据类型
  46. String cellValueByCell = getCellValueByCell(cell);
  47. System.out.println(cellValueByCell);
  48. }
  49. }
  50. System.out.println("----");
  51. }
  52. fileInputStream.close();
  53. }
  54. //获取单元格各类型值,返回字符串类型
  55. public static String getCellValueByCell(Cell cell) {
  56. //判断是否为null或空串
  57. if (cell == null || cell.toString().trim().equals("")) {
  58. return "";
  59. }
  60. String cellValue = "";
  61. CellType cellType = cell.getCellType();
  62. switch (cellType) {
  63. // 数字
  64. case NUMERIC:
  65. short format = cell.getCellStyle().getDataFormat();
  66. if (DateUtil.isCellDateFormatted(cell)) {
  67. SimpleDateFormat sdf = null;
  68. //System.out.println("cell.getCellStyle().getDataFormat()="+cell.getCellStyle().getDataFormat());
  69. if (format == 20 || format == 32) {
  70. sdf = new SimpleDateFormat("HH:mm");
  71. } else if (format == 14 || format == 31 || format == 57 || format == 58) {
  72. // 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58)
  73. sdf = new SimpleDateFormat("yyyy-MM-dd");
  74. double value = cell.getNumericCellValue();
  75. Date date = org.apache.poi.ss.usermodel.DateUtil
  76. .getJavaDate(value);
  77. cellValue = sdf.format(date);
  78. } else {
  79. // 日期
  80. sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  81. }
  82. try {
  83. // 日期
  84. cellValue = sdf.format(cell.getDateCellValue());
  85. } catch (Exception e) {
  86. try {
  87. throw new Exception("exception on get date data !".concat(e.toString()));
  88. } catch (Exception e1) {
  89. e1.printStackTrace();
  90. }
  91. } finally {
  92. sdf = null;
  93. }
  94. } else {
  95. BigDecimal bd = new BigDecimal(cell.getNumericCellValue());
  96. // 数值 这种用BigDecimal包装再获取plainString,可以防止获取到科学计数值
  97. cellValue = bd.toPlainString();
  98. }
  99. break;
  100. // 字符串
  101. case STRING:
  102. cellValue = cell.getStringCellValue();
  103. break;
  104. // Boolean
  105. case BOOLEAN:
  106. cellValue = cell.getBooleanCellValue() + "";
  107. break;
  108. // 公式
  109. case FORMULA:
  110. cellValue = cell.getCellFormula();
  111. break;
  112. // 空值
  113. case BLANK:
  114. cellValue = "";
  115. break;
  116. // 故障
  117. case ERROR:
  118. cellValue = "ERROR VALUE";
  119. break;
  120. default:
  121. cellValue = "UNKNOW VALUE";
  122. break;
  123. }
  124. return cellValue;
  125. }
  126. }

  1. import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
  2. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  3. import org.apache.poi.ss.usermodel.*;
  4. import java.io.FileInputStream;
  5. import java.io.IOException;
  6. public class GS {
  7. public static void main(String[] args) throws IOException {
  8. String path = "D:\\poi\\";
  9. FileInputStream fileInputStream = new FileInputStream(path + "计算公式.xls");
  10. // 1.创建一个工作簿。使得excel能操作的,这边他也能操作。
  11. Workbook workbook = new HSSFWorkbook(fileInputStream);
  12. // 2.得到表。
  13. Sheet sheet = workbook.getSheetAt(0);
  14. Row row = sheet.getRow(4);
  15. Cell cell = row.getCell(0);
  16. // 拿到计算公式
  17. FormulaEvaluator formulaEvaluator = new HSSFFormulaEvaluator((HSSFWorkbook) workbook);
  18. // 输出单元格内容
  19. CellType cellType = cell.getCellType();
  20. switch (cellType) {
  21. case FORMULA:
  22. String cellFormula = cell.getCellFormula();
  23. System.out.println(cellFormula);
  24. // 计算
  25. CellValue evaluate = formulaEvaluator.evaluate(cell);
  26. String cellValue = evaluate.formatAsString();
  27. System.out.println(cellValue);
  28. break;
  29. }
  30. }
  31. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/726146
推荐阅读
相关标签
  

闽ICP备14008679号