Java怎么把某个csv文件,写到指定的excel的sheet里?
rt
以下是一个使用Apache POI库将CSV文件数据写入Excel工作表的Java示例代码:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class CsvToExcel {
public static void main(String[] args) throws IOException {
String csvFilePath = "path/to/csv/file.csv";
String excelFilePath = "path/to/excel/file.xlsx";
String sheetName = "Sheet1";
List<String[]> data = readCsvFile(csvFilePath);
writeToExcel(data, excelFilePath, sheetName);
}
public static List<String[]> readCsvFile(String filePath) throws IOException {
List<String[]> data = new ArrayList<>();
try (FileInputStream inputStream = new FileInputStream(new File(filePath))) {
int lineNum = 0;
String line;
while ((line = inputStream.readLine()) != null) {
String[] values = line.split(",");
data.add(values);
lineNum++;
}
}
return data;
}
public static void writeToExcel(List<String[]> data, String excelFilePath, String sheetName) throws IOException {
try (FileOutputStream outputStream = new FileOutputStream(excelFilePath)) {
XSSFWorkbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet(sheetName);
int rowNum = 0;
Row row = sheet.createRow(rowNum++);
for (String[] values : data) {
for (int i = 0; i < values.length; i++) {
Cell cell = row.createCell(i);
cell.setCellValue(values[i]);
}
row = sheet.createRow(rowNum++);
}
workbook.write(outputStream);
}
}
}
3 回答2.2k 阅读✓ 已解决
3 回答3.7k 阅读✓ 已解决
8 回答2.9k 阅读
4 回答2.3k 阅读✓ 已解决
3 回答2.2k 阅读✓ 已解决
3 回答1.5k 阅读✓ 已解决
1 回答1.9k 阅读✓ 已解决
问题可以拆解成两步,读取CSV,写入Excel: