如何使用Java创建基于CSV文件的Excel文件? [英] How to create an Excel file based on CSV file using Java?
本文介绍了如何使用Java创建基于CSV文件的Excel文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要使用Java在CSV文件的基础上创建XLS文件。
I have a requirement to create an XLS file on the basis of a CSV file using Java.
请假定我最喜欢创建excel文件。
Please suppest to me which API is best to create excel file.
感谢
推荐答案
建议您使用 Apache POI框架(特别是
I suggest you use the Apache POI framework (specifically the HSSF / XSSF API) for writing out the XLS file.
为了读取CSV文件,我建议您使用 OpenCSV ,因为它会为您处理转义字符等。
For reading a CSV file I suggest you use OpenCSV as it will take care of escaped characters etc for you.
Putting together the POI example from here and the OpenCSV example from here gives you this:
import java.io.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import au.com.bytecode.opencsv.CSVReader;
class Test {
public static void main(String[] args) throws IOException {
Workbook wb = new HSSFWorkbook();
CreationHelper helper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("new sheet");
CSVReader reader = new CSVReader(new FileReader("data.csv"));
String[] line;
int r = 0;
while ((line = reader.readNext()) != null) {
Row row = sheet.createRow((short) r++);
for (int i = 0; i < line.length; i++)
row.createCell(i)
.setCellValue(helper.createRichTextString(line[i]));
}
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
}
}
这篇关于如何使用Java创建基于CSV文件的Excel文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文