网上得来终觉浅

_φ(❐_❐✧ 人丑就要多读书

导航

csv转excle

package com.test.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;

@Component
public class FileConverter {

    /**
     * csv文件转excel
     * @param filepath  文件路径,转换到同目录下
     * @param filename  文件名,转换为相同文件名
     * @return
     */
    public static String convertCsv2Excel(String filepath,String filename) {
        try {
//            String csvFileAddress = "F:\\bgt\\api\\aaaaaaaaaaa.csv"; //csv file address
//            String xlsxFileAddress = "F:\\bgt\\api\\aaaaaaaaaaa.xlsx"; //xlsx file address
            String csvFileAddress = filepath.concat(File.separator).concat(filename).concat(".csv");
            String xlsxFileAddress = filepath.concat(File.separator).concat(filename).concat(".xlsx");
            XSSFWorkbook workBook = new XSSFWorkbook();
            XSSFSheet sheet = workBook.createSheet("sheet1");
            String currentLine=null;
            int RowNum=0;
            BufferedReader br = new BufferedReader(new FileReader(csvFileAddress));
            while ((currentLine = br.readLine()) != null) {
                String str[] = currentLine.split(",");
                XSSFRow currentRow=sheet.createRow(RowNum);
                for(int i=0;i<str.length;i++){
                    currentRow.createCell(i).setCellValue(str[i]);
                }
                RowNum++;
            }

            FileOutputStream fileOutputStream =  new FileOutputStream(xlsxFileAddress);
            workBook.write(fileOutputStream);
            fileOutputStream.close();
            br.close();
            return xlsxFileAddress;
        } catch (Exception ex) {
            System.out.println(ex.getMessage()+"Exception in try");
        }
        return "";
    }
}

posted on 2022-05-25 15:27  bgtong  阅读(43)  评论(0编辑  收藏  举报