使用Apache poi将csv转换为xls/xlsx?

v0l*_*0rt 8 spring spring-mvc poi-hssf apache-poi xssf

我需要在我的项目中将csv转换为xls/xlsx?我怎样才能做到这一点?有人可以给我发一些例子吗?我想用Apache poi做这件事.我还需要从java端创建一个单元格.

San*_*ngh 17

您可以尝试使用以下方法使用apache-poi创建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");
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 得到它,我正在使用"|" 只有这意味着逻辑或,我应该使用"\\ |".谢谢 (2认同)

小智 6

我们可以使用 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" );
  }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

我发现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");
    }
Run Code Online (Sandbox Code Playgroud)


小智 5

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();
}
Run Code Online (Sandbox Code Playgroud)