在Java開發中,CSV與XLS轉換是常見的需求。CSV是指逗號分隔值文件,XLS則是指Microsoft Excel文件。本文將介紹如何使用Java實現CSV與XLS之間的轉換。
CSV轉換為XLS的過程很簡單,只需要利用Java提供的POI庫即可。以下是轉換的代碼:
File csvFile = new File("test.csv"); File xlsFile = new File("test.xls"); try (FileInputStream inputStream = new FileInputStream(csvFile)) { HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("Sheet1"); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; int rowNumber = 0; while ((line = reader.readLine()) != null) { String[] fields = line.split(","); HSSFRow row = sheet.createRow(rowNumber++); for (int i = 0; i< fields.length; i++) { HSSFCell cell = row.createCell(i); cell.setCellValue(fields[i]); } } FileOutputStream outputStream = new FileOutputStream(xlsFile); workbook.write(outputStream); } catch (IOException e) { e.printStackTrace(); }
以上代碼將把test.csv導出為test.xls文件。
反過來,將XLS轉換為CSV則需要借助第三方庫。下面以使用JExcelAPI為例:
File xlsFile = new File("test.xls"); File csvFile = new File("test.csv"); try (InputStream inputStream = new FileInputStream(xlsFile)) { Workbook workbook = Workbook.getWorkbook(inputStream); Sheet sheet = workbook.getSheet(0); BufferedWriter writer = new BufferedWriter(new FileWriter(csvFile)); for (int row = 0; row< sheet.getRows(); row++) { for (int col = 0; col< sheet.getColumns(); col++) { writer.write(sheet.getCell(col, row).getContents()); if (col< sheet.getColumns() - 1) { writer.write(","); } } writer.newLine(); } writer.flush(); writer.close(); } catch (Exception e) { e.printStackTrace(); }
以上代碼將test.xls導出為test.csv文件。