java代码xlsx转换成csv
时间: 2023-07-28 19:09:48 浏览: 102
你可以使用 Apache POI 库来读取 XLSX 文件并将其转换为 CSV 格式。以下是一个简单的示例代码:
```java
import java.io.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
public class XlsxToCsvConverter {
public static void main(String[] args) {
try {
FileInputStream fileInputStream = new FileInputStream("input.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);
XSSFSheet sheet = workbook.getSheetAt(0);
FileWriter fileWriter = new FileWriter("output.csv");
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
for (Row row : sheet) {
for (Cell cell : row) {
String cellValue = "";
switch (cell.getCellTypeEnum()) {
case STRING:
cellValue = cell.getStringCellValue();
break;
case NUMERIC:
cellValue = String.valueOf(cell.getNumericCellValue());
break;
case BOOLEAN:
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
default:
break;
}
bufferedWriter.write(cellValue + ",");
}
bufferedWriter.newLine();
}
bufferedWriter.close();
fileWriter.close();
workbook.close();
fileInputStream.close();
System.out.println("XLSX file converted to CSV successfully!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
你需要将 `input.xlsx` 替换为实际的 XLSX 文件名,将 `output.csv` 替换为实际的输出文件名。该代码将 XLSX 文件的第一个工作表转换为 CSV 格式,并将其写入到输出文件中。
阅读全文