Java教程

JAVA代码csv转excel

本文主要是介绍JAVA代码csv转excel,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

直接上代码

  1 import org.apache.poi.xssf.usermodel.XSSFRow;
  2 import org.apache.poi.xssf.usermodel.XSSFSheet;
  3 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  4 import org.jumpmind.symmetric.csv.CsvReader;
  5 import org.slf4j.Logger;
  6 import org.slf4j.LoggerFactory;
  7 
  8 import java.io.*;
  9 import java.nio.charset.Charset;
 10 
 11 /**
 12  *-----------------------maven 依赖----------------------------
 13  * CSV解析依赖包
 14  * <dependency>
 15  *      <groupId>org.jumpmind.symmetric</groupId>
 16  *      <artifactId>symmetric-csv</artifactId>
 17  *      <version>3.5.19</version>
 18  * </dependency>
 19  *
 20  * APACHE POI包
 21  * <dependency>
 22  *      <groupId>org.apache.poi</groupId>
 23  *      <artifactId>poi-ooxml</artifactId>
 24  *      <version>3.17</version>
 25  * </dependency>
 26  *
 27  * -----------------------------------------------------------
 28  *
 29  * @date 2021/8/5
 30  * @description
 31  */
 32 public class CsvToXlsxUtil {
 33 
 34     private static final Logger log = LoggerFactory.getLogger(CsvToXlsxUtil.class);
 35 
 36     //CSV常用分隔符,如需动态扩展设置成配置项
 37     private static final char[] DELIMITERS = {
 38             ',',
 39             ';',
 40             '\001',
 41             ' ',
 42             '\t',
 43             '|',
 44             '#',
 45             '&'
 46     };
 47 
 48 
 49     public static void main(String[] args) {
 50         String csvFile = "D:/temp/cy/cy_3.csv";
 51         System.out.println(csvToXLSX(csvFile));
 52     }
 53 
 54     /**
 55      * 读取CSV文件并写入到XLSX文件中,默认编码
 56      * @param csvFileAddress
 57      * @return
 58      */
 59     public static String csvToXLSX(String csvFileAddress) {
 60         return csvToXLSX(csvFileAddress,"UTF-8");
 61     }
 62 
 63     /**
 64      * 读取CSV文件并写入到XLSX文件中,指定CSV文件编码
 65      * @param csvFileAddress
 66      * @param charset
 67      * @return
 68      */
 69     public static String csvToXLSX(String csvFileAddress,String charset) {
 70         String xlsxFileAddress = "";
 71         FileOutputStream fileOutputStream = null;
 72         try {
 73             char delimiter = getDelimiter(csvFileAddress);
 74             xlsxFileAddress = csvFileAddress.replace("csv","xlsx"); //xlsx file address
 75             XSSFWorkbook workBook = new XSSFWorkbook();
 76             XSSFSheet sheet = workBook.createSheet(getSheetName(csvFileAddress));
 77             int RowNum=-1;
 78             CsvReader csvReader = new CsvReader(csvFileAddress, delimiter, Charset.forName(charset));
 79             while (csvReader.readRecord()){
 80                 RowNum++;
 81                 XSSFRow currentRow=sheet.createRow(RowNum);
 82                 for(int i=0;i<csvReader.getColumnCount();i++){
 83                     currentRow.createCell(i).setCellValue(csvReader.get(i));
 84                 }
 85             }
 86             fileOutputStream =  new FileOutputStream(xlsxFileAddress);
 87             workBook.write(fileOutputStream);
 88             return getFileName(xlsxFileAddress);
 89         } catch (Exception e) {
 90             log.error("CsvToXlsxUtil exception :" , e);
 91         }finally {
 92             try {
 93                 fileOutputStream.close();
 94             } catch (IOException e) {
 95                 log.error("CsvToXlsxUtil close FileOutputStream exception :" , e);
 96             }
 97         }
 98         return getFileName(xlsxFileAddress);
 99     }
100 
101 
102     /**
103      * 设置excel文件的sheet名称
104      * 获取CSV文件名作为Excel文件的sheet名称
105      * @param path
106      * @return
107      */
108     private static String getSheetName(String path){
109         try {
110             String[] file = getFileName(path).split("\\.");
111             return file[0];
112         }catch (Exception e){
113             log.error("CsvToXlsxUtil get sheet name exception : ",e);
114             return "Sheet";
115         }
116     }
117 
118 
119     /**
120      * 根据资源路径切割获取文件名
121      * @param path
122      * @return
123      */
124     private static String getFileName(String path){
125         String[] paths = path.contains("\\")?path.split("\\\\"):path.split("/");
126         return paths[paths.length-1];
127     }
128 
129     /**
130      * 常用CSV分隔符数组遍历资源第一行,分隔的字段数多的为资源分隔符
131      * 异常情况下默认用’,‘作为分隔符
132      * @param path 资源路径
133      * @return
134      */
135     private static char getDelimiter(String path){
136         BufferedReader br = null;
137         char delimiter = ',';
138         try {
139             br = new BufferedReader(new FileReader(path));
140             String line = br.readLine();
141             CsvReader csvReader;
142             int columCount = 0;
143             for (char delimiterTest : DELIMITERS){
144                 csvReader = new CsvReader(getStringStream(line),delimiterTest,Charset.forName("UTF-8"));
145                 if(csvReader.readRecord()){
146                     int newColumnCount = csvReader.getColumnCount();
147                     if(newColumnCount>columCount){
148                         columCount = newColumnCount;
149                         delimiter = delimiterTest;
150                     }
151                 }
152             }
153         } catch (Exception e) {
154             log.error("CsvToXlsxUtil get delimiter exception :",e);
155         }finally {
156             try {
157                 br.close();
158             } catch (IOException e) {
159                 log.error("CsvToXlsxUtil get delimiter close BufferedReader exception :",e);
160             }
161         }
162         return delimiter;
163     }
164 
165 
166     /**
167      * 字符串转输入流
168      * 把CSV文件第一行数据转成输入流
169      * @param sInputString
170      * @return
171      */
172     private static InputStream getStringStream(String sInputString){
173         if (sInputString != null && !sInputString.equals("")){
174             try{
175                 ByteArrayInputStream tInputStringStream = new ByteArrayInputStream(sInputString.getBytes());
176                 return tInputStringStream;
177             }catch (Exception e){
178                 log.error("CsvToXlsxUtil get StringStream exception :",e);
179             }
180         }
181         return null;
182     }
183 }

 

这篇关于JAVA代码csv转excel的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!