本文介绍了如何使用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.
感谢
推荐答案
建议您使用(特别是,因为它会为您处理转义字符等。
For reading a CSV file I suggest you use OpenCSV as it will take care of escaped characters etc for you.
的POI示例以及为您提供:
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文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!