Java 读取 CSV 文件并将其写入指定 Excel 工作表?

Java怎么把某个csv文件,写到指定的excel的sheet里?

rt

阅读 825
avatarAI BotBETA

以下是一个使用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);
        }
    }
}
1 个回答

问题可以拆解成两步,读取CSV,写入Excel:

//参考链接:https://www.grapecity.com.cn/developer/grapecitydocuments/excel-java/docs/ManageFileOperations/ImportandExportCSVFile
public void ImportCSV(){
    Workbook csvWb = new Workbook();
    //打开需要导入的CSV文件
    csvWb.open("resources/ImportCsv.csv");
    Workbook wb = new Workbook();    
    //获取CSV数据的区域
    IRange csvRange = csvWb.getWorksheets().get(0).getUsedRange();
    //获取目标工作表的区域
    IRange targetRange = wb.getWorksheets().get(0).getRange("A1:D10");
    //把CSV数据复制到目标工作表区域中
    csvRange.copy(targetRange);
    wb.save("output/importCsv.xlsx");
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏