首先引入apache poi的依赖

1
2 org.apache.poi
3 poi
4 3.8
5

示例一:在桌面上生成一个Excel文件

复制代码
1 public static void createExcel() throws IOException{
2 // 获取桌面路径
3 FileSystemView fsv = FileSystemView.getFileSystemView();
4 String desktop = fsv.getHomeDirectory().getPath();
5 String filePath = desktop + "/template.xls";
6
7 File file = new File(filePath);
8 OutputStream outputStream = new FileOutputStream(file);
9 HSSFWorkbook workbook = new HSSFWorkbook();
10 HSSFSheet sheet = workbook.createSheet("Sheet1");
11 HSSFRow row = sheet.createRow(0);
12 row.createCell(0).setCellValue("id");
13 row.createCell(1).setCellValue("订单号");
14 row.createCell(2).setCellValue("下单时间");
15 row.createCell(3).setCellValue("个数");
16 row.createCell(4).setCellValue("单价");
17 row.createCell(5).setCellValue("订单金额");
18 row.setHeightInPoints(30); // 设置行的高度
19
20 HSSFRow row1 = sheet.createRow(1);
21 row1.createCell(0).setCellValue("1");
22 row1.createCell(1).setCellValue("NO00001");
23
24 // 日期格式化
25 HSSFCellStyle cellStyle2 = workbook.createCellStyle();
26 HSSFCreationHelper creationHelper = workbook.getCreationHelper();
27 cellStyle2.setDataFormat(creationHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));
28 sheet.setColumnWidth(2, 20 256); // 设置列的宽度
29
30 HSSFCell cell2 = row1.createCell(2);
31 cell2.setCellStyle(cellStyle2);
32 cell2.setCellValue(new Date());
33
34 row1.createCell(3).setCellValue(2);
35
36
37 // 保留两位小数
38 HSSFCellStyle cellStyle3 = workbook.createCellStyle();
39 cellStyle3.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));
40 HSSFCell cell4 = row1.createCell(4);
41 cell4.setCellStyle(cellStyle3);
42 cell4.setCellValue(29.5);
43
44
45 // 货币格式化
46 HSSFCellStyle cellStyle4 = workbook.createCellStyle();
47 HSSFFont font = workbook.createFont();
48 font.setFontName("华文行楷");
49 font.setFontHeightInPoints((short)15);
50 font.setColor(HSSFColor.RED.index);
51 cellStyle4.setFont(font);
52
53 HSSFCell cell5 = row1.createCell(5);
54 cell5.setCellFormula("D2
E2"); // 设置计算公式
55
56 // 获取计算公式的值
57 HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(workbook);
58 cell5 = e.evaluateInCell(cell5);
59 System.out.println(cell5.getNumericCellValue());
60
61
62 workbook.setActiveSheet(0);
63 workbook.write(outputStream);
64 outputStream.close();
65 }
复制代码

示例2:读取Excel,解析数据

复制代码
1 public static void readExcel() throws IOException{
2 FileSystemView fsv = FileSystemView.getFileSystemView();
3 String desktop = fsv.getHomeDirectory().getPath();
4 String filePath = desktop + "/template.xls";
5
6 FileInputStream fileInputStream = new FileInputStream(filePath);
7 BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
8 POIFSFileSystem fileSystem = new POIFSFileSystem(bufferedInputStream);
9 HSSFWorkbook workbook = new HSSFWorkbook(fileSystem);
10 HSSFSheet sheet = workbook.getSheet("Sheet1");
11
12 int lastRowIndex = sheet.getLastRowNum();
13 System.out.println(lastRowIndex);
14 for (int i = 0; i <= lastRowIndex; i++) {
15 HSSFRow row = sheet.getRow(i);
16 if (row == null) { break; }
17
18 short lastCellNum = row.getLastCellNum();
19 for (int j = 0; j < lastCellNum; j++) {
20 String cellValue = row.getCell(j).getStringCellValue();
21 System.out.println(cellValue);
22 }
23 }
24
25 bufferedInputStream.close();
26 }
复制代码

四:Java Web 中导出和导入Excel

1、导出示例

复制代码
1 @SuppressWarnings("resource")
2 @RequestMapping("/export")
3 public void exportExcel(HttpServletResponse response, HttpSession session, String name) throws Exception {
4
5 String[] tableHeaders = {"id", "姓名", "年龄"};
6
7 HSSFWorkbook workbook = new HSSFWorkbook();
8 HSSFSheet sheet = workbook.createSheet("Sheet1");
9 HSSFCellStyle cellStyle = workbook.createCellStyle();
10 cellStyle.setAlignment(HorizontalAlignment.CENTER);
11 cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
12
13 Font font = workbook.createFont();
14 font.setColor(HSSFColor.RED.index);
15 font.setBold(true);
16 cellStyle.setFont(font);
17
18 // 将第一行的三个单元格给合并
19 sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2));
20 HSSFRow row = sheet.createRow(0);
21 HSSFCell beginCell = row.createCell(0);
22 beginCell.setCellValue("通讯录");
23 beginCell.setCellStyle(cellStyle);
24
25 row = sheet.createRow(1);
26 // 创建表头
27 for (int i = 0; i < tableHeaders.length; i++) {
28 HSSFCell cell = row.createCell(i);
29 cell.setCellValue(tableHeaders[i]);
30 cell.setCellStyle(cellStyle);
31 }
32
33 List users = new ArrayList<>();
34 users.add(new User(1L, "张三", 20));
35 users.add(new User(2L, "李四", 21));
36 users.add(new User(3L, "王五", 22));
37
38 for (int i = 0; i < users.size(); i++) {
39 row = sheet.createRow(i + 2);
40
41 User user = users.get(i);
42 row.createCell(0).setCellValue(user.getId());
43 row.createCell(1).setCellValue(user.getName());
44 row.createCell(2).setCellValue(user.getAge());
45 }
46
47 OutputStream outputStream = response.getOutputStream();
48 response.reset();
49 response.setContentType("application/vnd.ms-excel");
50 response.setHeader("Content-disposition", "attachment;filename=template.xls");
51
52 workbook.write(outputStream);
53 outputStream.flush();
54 outputStream.close();
55 }
复制代码

2、导入示例

  1、使用SpringMVC上传文件,需要用到commons-fileupload

  

1
2 commons-fileupload
3 commons-fileupload
4 1.3
5

  2、需要在spring的配置文件中配置一下multipartResolver

1 2 class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
3
4

  3、index.jsp

复制代码
1 导出

2
3


4
5
6

复制代码

  4、解析上传的.xls文件

复制代码
1 @SuppressWarnings("resource")
2 @RequestMapping("/import")
3 public void importExcel(@RequestParam("file") MultipartFile file) throws Exception{
4 InputStream inputStream = file.getInputStream();
5 BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
6 POIFSFileSystem fileSystem = new POIFSFileSystem(bufferedInputStream);
7 HSSFWorkbook workbook = new HSSFWorkbook(fileSystem);
8 //HSSFWorkbook workbook = new HSSFWorkbook(file.getInputStream());
9 HSSFSheet sheet = workbook.getSheetAt(0);
10
11 int lastRowNum = sheet.getLastRowNum();
12 for (int i = 2; i <= lastRowNum; i++) {
13 HSSFRow row = sheet.getRow(i);
14 int id = (int) row.getCell(0).getNumericCellValue();
15 String name = row.getCell(1).getStringCellValue();
16 int age = (int) row.getCell(2).getNumericCellValue();
17
18 System.out.println(id + "-" + name + "-" + age);
19 }
20 }
深圳网站建设www.sz886.com