java csv to excel_用java怎么把指定的csv文件,写到指定的excel的sheet里?
时间: 2024-02-26 17:57:16 浏览: 175
你可以使用Apache POI库来实现将CSV文件写入Excel的Sheet中。下面是一个简单的Java代码示例:
```java
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
public class CSVtoExcelConverter {
public static void main(String[] args) {
String csvFilePath = "path/to/csv/file.csv";
String excelFilePath = "path/to/excel/file.xls";
String sheetName = "Sheet1";
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(new FileInputStream(csvFilePath), "UTF-8"));
Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet(sheetName);
String line;
int rowNumber = 0;
while ((line = reader.readLine()) != null) {
Row row = sheet.createRow(rowNumber++);
String[] columns = line.split(",");
int columnNumber = 0;
for (String column : columns) {
row.createCell(columnNumber++).setCellValue(column);
}
}
reader.close();
workbook.write(new FileOutputStream(excelFilePath));
workbook.close();
System.out.println("CSV file converted to Excel successfully.");
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
```
在这个例子中,我们使用BufferedReader读取CSV文件,然后使用HSSFWorkbook创建Excel工作簿和Sheet对象。我们读取CSV文件的每一行,将行分割为列,并将每一列写入Excel的行中。最后,我们将Excel文件写入磁盘并关闭工作簿。
阅读全文