toshine

导航

java生成Excel或CSV文件并写入数据

引入Maven依赖:

 1     <dependency>
 2       <groupId>org.apache.poi</groupId>
 3       <artifactId>poi</artifactId>
 4       <version>3.17</version>
 5     </dependency>
 6     <dependency>
 7       <groupId>org.apache.poi</groupId>
 8       <artifactId>poi-ooxml</artifactId>
 9       <version>3.17</version>
10     </dependency>

Java将数据写入Excel,把这个方法封装了WriteToExcel

 1 import org.apache.poi.xssf.usermodel.XSSFCell;
 2 import org.apache.poi.xssf.usermodel.XSSFRow;
 3 import org.apache.poi.xssf.usermodel.XSSFSheet;
 4 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 5  
 6 import java.io.File;
 7 import java.io.FileOutputStream;
 8 import java.io.IOException;
 9 import java.util.ArrayList;
10 import java.util.List;
11  
12 public class WriteToExcel {
13  
14     private static XSSFWorkbook workbook;
15     private static XSSFSheet sheet;
16     private static XSSFRow row;
17     private static XSSFCell cell;
18     private static File file;
19  
20     //创建sheet页
21     public static void setSheet(String sheetName) {
22         workbook = new XSSFWorkbook();
23         sheet = workbook.createSheet(sheetName);
24     }
25     //创建表头
26     public static void createHead(List<String> headList) {
27         //创建表头,也就是第一行
28         row = sheet.createRow(0);
29         for (int i = 0; i < headList.size(); i++) {
30             cell = row.createCell(i);
31             cell.setCellValue(headList.get(i));
32         }
33     }
34     //创建表内容
35     public static void createContent(List<List<String>> contentList) {
36         //创建表内容,从第二行开始
37         for (int i = 0; i < contentList.size(); i++) {
38             row = sheet.createRow(i + 1);
39             for (int j = 0; j < contentList.get(i).size(); j++) {
40                 row.createCell(j).setCellValue(contentList.get(i).get(j));
41             }
42         }
43     }
44     //写入文件
45     public static void writeToFile(String filePath){
46         file = new File(filePath);
47         //将文件保存到指定的位置
48         try {
49             workbook.write(new FileOutputStream(file));
50             System.out.println("写入成功");
51             workbook.close();
52         } catch (IOException e) {
53             e.printStackTrace();
54         }
55     }
56     // 内容测试数据
57     protected static List<List<String>> getContent() {
58         List<List<String>> contentList = new ArrayList<>();
59         List<String> content1 = new ArrayList<>();
60         content1.add("张三");
61         content1.add("18");
62         List<String> content2 = new ArrayList<>();
63         content2.add("李四");
64         content2.add("20");
65         contentList.add(content1);
66         contentList.add(content2);
67         return contentList;
68     }
69     
70     public static void main(String[] args) {
71         //表头测试数据
72         List<String> headList = new ArrayList<>();
73         headList.add("昵称");
74         headList.add("年龄");
75         List<List<String>> contentList = getContent();//内容测试数据
76         setSheet("WorkSheet");                        //创建sheet页
77         createHead(headList);                         //设置表头
78         createContent(contentList);                   //设置内容
79         writeToFile("D://work.xls");         //写入文件
80     }
81 }
View Code

将excel转换为csv

 1 import org.apache.commons.io.FilenameUtils;
 2 import org.apache.poi.ss.usermodel.Cell;
 3 import org.apache.poi.xssf.usermodel.XSSFCell;
 4 import org.apache.poi.xssf.usermodel.XSSFRow;
 5 import org.apache.poi.xssf.usermodel.XSSFSheet;
 6 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 7 
 8 import java.io.File;
 9 import java.io.FileInputStream;
10 import java.io.FileOutputStream;
11 import java.util.Iterator;
12 
13 /**
14  * @Description: XlsxtoCSV
15  * @author: muxianghui
16  * @date: 2023年04月27日 9:56
17  */
18 public class XlsxtoCSV {
19     public static void xlsx(File inputFile, File outputFile) {
20         StringBuffer data = new StringBuffer();
21         try {
22             FileOutputStream fos = new FileOutputStream(outputFile);
23             FileInputStream fis = new FileInputStream(inputFile);
24             XSSFWorkbook workbook = null;
25 
26             String ext = FilenameUtils.getExtension(inputFile.toString());
27 
28             if (ext.equalsIgnoreCase("xlsx")) {
29                 workbook = new XSSFWorkbook(fis);
30             } else if (ext.equalsIgnoreCase("xls")) {
31                 workbook = new XSSFWorkbook(fis);
32             }
33             int numberOfSheets = workbook.getNumberOfSheets();
34             XSSFRow row;
35             XSSFCell cell;
36             for (int i = 0; i < numberOfSheets; i++) {
37                 XSSFSheet sheet = workbook.getSheetAt(0);
38                 Iterator rowIterator = sheet.iterator();
39 
40                 while (rowIterator.hasNext()) {
41                     row = (XSSFRow) rowIterator.next();
42                     Iterator cellIterator = row.cellIterator();
43                     while (cellIterator.hasNext()) {
44 
45                         cell = (XSSFCell) cellIterator.next();
46 
47                         switch (cell.getCellType()) {
48                             case Cell.CELL_TYPE_BOOLEAN:
49                                 data.append(cell.getBooleanCellValue() + ",");
50 
51                                 break;
52                             case Cell.CELL_TYPE_NUMERIC:
53                                 data.append(cell.getNumericCellValue() + ",");
54 
55                                 break;
56                             case Cell.CELL_TYPE_STRING:
57                                 data.append(cell.getStringCellValue() + ",");
58                                 break;
59 
60                             case Cell.CELL_TYPE_BLANK:
61                                 data.append("" + ",");
62                                 break;
63                             default:
64                                 data.append(cell + ",");
65 
66                         }
67                     }
68                     data.append('\n'); // appending new line after each row
69                 }
70 
71             }
72             fos.write(data.toString().getBytes());
73             fos.close();
74         } catch (Exception ioe) {
75             ioe.printStackTrace();
76         }
77     }

注意事项:

如果打开文件提示“文件格式和扩展名不匹配。。。”,立刻想到这是由于生成的文件有问题。

解决一:需要修改代码重新生成;

解决二:通过文件转换方式生成;

posted on 2023-04-27 11:04  加瓦开阀攻城狮  阅读(591)  评论(0)    收藏  举报

……