Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring 使用ApachePOI将csv转换为xls/xlsx?_Spring_Spring Mvc_Apache Poi_Xssf_Poi Hssf - Fatal编程技术网

Spring 使用ApachePOI将csv转换为xls/xlsx?

Spring 使用ApachePOI将csv转换为xls/xlsx?,spring,spring-mvc,apache-poi,xssf,poi-hssf,Spring,Spring Mvc,Apache Poi,Xssf,Poi Hssf,我需要在我的项目中将csv转换为xls/xlsx?我该怎么做?有人能给我举一些例子吗?我想用ApachePOI做这件事。我还需要从java端创建一个单元格。您可以尝试以下方法使用ApachePOI创建xlsx文件 public static void csvToXLSX() { try { String csvFileAddress = "test.csv"; //csv file address String xlsxFileAddress = "tes

我需要在我的项目中将csv转换为xls/xlsx?我该怎么做?有人能给我举一些例子吗?我想用ApachePOI做这件事。我还需要从java端创建一个单元格。

您可以尝试以下方法使用ApachePOI创建xlsx文件

public static void csvToXLSX() {
    try {
        String csvFileAddress = "test.csv"; //csv file address
        String xlsxFileAddress = "test.xlsx"; //xlsx file address
        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(",");
            RowNum++;
            XSSFRow currentRow=sheet.createRow(RowNum);
            for(int i=0;i<str.length;i++){
                currentRow.createCell(i).setCellValue(str[i]);
            }
        }

        FileOutputStream fileOutputStream =  new FileOutputStream(xlsxFileAddress);
        workBook.write(fileOutputStream);
        fileOutputStream.close();
        System.out.println("Done");
    } catch (Exception ex) {
        System.out.println(ex.getMessage()+"Exception in try");
    }
}
公共静态void csvToXLSX(){
试一试{
字符串csvFileAddress=“test.csv”//csv文件地址
字符串xlsxFileAddress=“test.xlsx”;//xlsx文件地址
XSSFWorkbook工作簿=新XSSFWorkbook();
XSSFSheet sheet=workBook.createSheet(“sheet1”);
字符串currentLine=null;
int RowNum=0;
BufferedReader br=新的BufferedReader(新文件读取器(csvFileAddress));
而((currentLine=br.readLine())!=null){
字符串str[]=currentLine.split(“,”);
RowNum++;
XSSFRow currentRow=sheet.createRow(RowNum);

对于(int i=0;i我们可以使用SXSSF Jar,在其中我们可以解析一个长文件,如下所示:

public static void main( String[] args ) {
  try {

    //   String fName = args[ 0 ];

    String csvFileAddress = "C:\\Users\\psingh\\Desktop\\test\\New folder\\GenericDealerReport - version6.txt"; //csv file address
    String xlsxFileAddress = "C:\\Users\\psingh\\Desktop\\trial\\test3.xlsx"; //xlsx file address

    SXSSFWorkbook workBook = new SXSSFWorkbook( 1000 );
    org.apache.poi.ss.usermodel.Sheet sheet = workBook.createSheet( "sheet1" );
    String currentLine = null;
    int RowNum = -1;
    BufferedReader br = new BufferedReader( new FileReader( csvFileAddress ) );
    while ( ( currentLine = br.readLine() ) != null ) {
      String str[] = currentLine.split( "\\|" );
      RowNum++;
      Row currentRow = sheet.createRow( RowNum );
      for ( int i = 0; i < str.length; i++ ) {
        currentRow.createCell( i )
                .setCellValue( str[ i ] );
      }
    }
    DateFormat df = new SimpleDateFormat( "yyyy-mm-dd-HHmmss" );
    Date today = Calendar.getInstance()
                       .getTime();
    String reportDate = df.format( today );
    FileOutputStream fileOutputStream = new FileOutputStream( xlsxFileAddress );
    workBook.write( fileOutputStream );
    fileOutputStream.close();
    //System.out.println( "Done" );
  }
  catch ( Exception ex ) {
    System.out.println( ex.getMessage() + "Exception in try" );
  }
}
publicstaticvoidmain(字符串[]args){
试一试{
//字符串fName=args[0];
String csvFileAddress=“C:\\Users\\psingh\\Desktop\\test\\New folder\\GenericDealerReport-version6.txt”;//csv文件地址
String xlsxFileAddress=“C:\\Users\\psingh\\Desktop\\trial\\test3.xlsx”//xlsx文件地址
SXSSFWorkbook工作簿=新SXSSFWorkbook(1000);
org.apache.poi.ss.usermodel.Sheet Sheet=workBook.createSheet(“sheet1”);
字符串currentLine=null;
int RowNum=-1;
BufferedReader br=新的BufferedReader(新文件读取器(csvFileAddress));
而((currentLine=br.readLine())!=null){
字符串str[]=currentLine.split(“\\\\”);
RowNum++;
Row currentRow=sheet.createRow(RowNum);
对于(int i=0;i
我发现
SXSSFWorkbook
XSSFWorkbook
快得多。下面是修改后的代码:

try {
        String csvFileInput = "inputFile.csv";
        String xlsxFileOutput ="outputFile.xls";

        LOGGER.error(csvFileInput);
        LOGGER.error( xlsxFileOutput);
        SXSSFWorkbook workBook = new SXSSFWorkbook();
        Sheet sheet = workBook.createSheet(transformBean.getOutputFileName());
        String currentLine = null;
        int RowNum = 0;
        BufferedReader br = new BufferedReader(new FileReader(csvFileInput));
        while ((currentLine = br.readLine()) != null) {
            String str[] = currentLine.split(",");
            RowNum++;
            Row currentRow = sheet.createRow(RowNum);
            for (int i = 0; i < str.length; i++) {
                currentRow.createCell(i).setCellValue(str[i]);
            }
        }
        FileOutputStream fileOutputStream = new FileOutputStream(xlsxFileOutput);
        workBook.write(fileOutputStream);
        fileOutputStream.close();
        System.out.println("Done");
    } catch (Exception ex) {
        System.out.println(ex.getMessage() + "Found Exception");
    }
试试看{
字符串csvFileInput=“inputFile.csv”;
字符串xlsxFileOutput=“outputFile.xls”;
记录器错误(csvFileInput);
LOGGER.error(xlsxFileOutput);
SXSSFWorkbook工作簿=新的SXSSFWorkbook();
Sheet Sheet=workBook.createSheet(transformBean.getOutputFileName());
字符串currentLine=null;
int RowNum=0;
BufferedReader br=新的BufferedReader(新文件读取器(csvFileInput));
而((currentLine=br.readLine())!=null){
字符串str[]=currentLine.split(“,”);
RowNum++;
Row currentRow=sheet.createRow(RowNum);
对于(int i=0;i
if(新文件(newFileName).isFile()返回;
@抑制警告(“资源”)
HSSFWorkbook wb=新的HSSFWorkbook();
第xlsRow行;
细胞xlsCell;
HSSFSheet sheet=wb.createSheet(“sheet1”);
int rowIndex=0;
for(CSVRecord记录:CSVFormat.EXCEL.parse(新文件读取器(文件名))){
xlsRow=sheet.createRow(行索引);
对于(int i=0;i
如果你有inputstream,试试这个 公共静态XSSFWorkbook csvToXLSX(InputStream InputStream)引发IOException{ XSSFWorkbook工作簿=新XSSFWorkbook()

try(BufferedReader br=new BufferedReader(new InputStreamReader(inputStream))){
工作表=工作簿。创建工作表(“工作表1”);
字符串currentLine=null;
int rowNum=0;
而((currentLine=br.readLine())!=null){
字符串[]str=currentLine.split(“,”);
rowNum++;
Row currentRow=sheet.createRow(rowNum);
for(int i=0;i
publicstaticvoidconvertCsvtoxlsX(stringxlsLocation,stringcsvLocation)引发异常{
SXSSFWorkbook工作簿=新的SXSSFWorkbook();
SXSSFSheet sheet=workbook.createSheet(“sheet”);
AtomicReference行=新的AtomicReference(0);
Files.readAllLines(path.get(csvLocation)).forEach(line->{
Row currentRow=sheet.createRow(Row.getAndSet(Row.get()+1));
String[]nextLine=line.split(“,”);
Stream.iterate(0,i->i+1).limit(nextLine.length).forEach(i->{
currentRow.createCell(i).setCellValue(nextLine[i]);
});
});
FileOutputStream fos=新的FileOutputStream(新文件(xlsLocation));
练习册。写作(fos);
fos.flush();
}

谢谢,但我的csv是|分隔的。当我用pipi替换逗号时,每个单元格有一个字符。我该怎么办?请确认您只使用了“|”或“\\\\\”。明白了,我只使用了“|”,这意味着逻辑或,我应该使用“\\\\\\\\”。谢谢这在第行引发了一个异常:“XSSF工作簿=新XSSF工作簿(),”说“NoClassDefFoundError”。你应该遵循命名约定。这意味着
rowNum
而不是
rowNum
if(new File(newFileName).isFile()) return;
    @SuppressWarnings("resource")
    HSSFWorkbook wb = new HSSFWorkbook();
    Row xlsRow;
    Cell xlsCell;
    HSSFSheet sheet = wb.createSheet("sheet1");
    int rowIndex = 0;
    for(CSVRecord record : CSVFormat.EXCEL.parse(new FileReader(fileName))) {
        xlsRow = sheet.createRow(rowIndex);
        for(int i = 0; i < record.size(); i ++){
            xlsCell = xlsRow.createCell(i);
            xlsCell.setCellValue(record.get(i));
        }
        rowIndex ++;
    }
    FileOutputStream out = new FileOutputStream(newFileName);
    wb.write(out);
    out.close();
    try(BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
        Sheet sheet = workBook.createSheet("sheet1");
        String currentLine=null;
        int rowNum=0;

        while ((currentLine = br.readLine()) != null) {
            String[] str = currentLine.split(",");
            rowNum++;
            Row currentRow=sheet.createRow(rowNum);
            for(int i=0;i<str.length;i++){
                currentRow.createCell(i).setCellValue(str[i]);
            }
        }

        log.info("CSV file converted to the workbook");
        return workBook;
    } catch (Exception ex) {
        log.error("Exception while converting csv to xls {}",ex);
    }finally {
        if (Objects.nonNull(workBook)) {
            workBook.close();
        }
    }
    return workBook;
}
public static void convertCsvToXlsx(String xlsLocation, String csvLocation) throws Exception {
    SXSSFWorkbook workbook = new SXSSFWorkbook();
    SXSSFSheet sheet = workbook.createSheet("Sheet");
    AtomicReference<Integer> row = new AtomicReference<>(0);
    Files.readAllLines(Paths.get(csvLocation)).forEach(line -> {
        Row currentRow = sheet.createRow(row.getAndSet(row.get() + 1));
        String[] nextLine = line.split(",");
        Stream.iterate(0, i -> i + 1).limit(nextLine.length).forEach(i -> {
            currentRow.createCell(i).setCellValue(nextLine[i]);
        });
    });
    FileOutputStream fos = new FileOutputStream(new File(xlsLocation));
    workbook.write(fos);
    fos.flush();
}