无法将.csv文件转换为.xls格式



我正在使用此代码将CSV文件转换为Excel。但是我在转换后的 excel 文件中只获得了 2 列的记录。可以对此代码进行哪些更改..

public static void main(String[] args) throws Exception {    
/* Step -1 : Read input CSV file in Java */
String inputCSVFile = "csv_2_xls.csv";
CSVReader reader = new CSVReader(new FileReader(inputCSVFile));
/* Variables to loop through the CSV File */
String [] nextLine; /* for every line in the file */            
int lnNum = 0; /* line number */
/* Step -2 : Define POI Spreadsheet objects */          
HSSFWorkbook new_workbook = new HSSFWorkbook(); //create a blank workbook object
HSSFSheet sheet = new_workbook.createSheet("CSV2XLS");  //create a worksheet with caption score_details
/* Step -3: Define logical Map to consume CSV file data into excel */
Map<String, Object[]> excel_data = new HashMap<String, Object[]>(); //create a map and define data
/* Step -4: Populate data into logical Map */
while ((nextLine = reader.readNext()) != null) {
lnNum++;                        
excel_data.put(Integer.toString(lnNum), new Object[] {nextLine[0],nextLine[1]});                        
}
/* Step -5: Create Excel Data from the map using POI */
Set<String> keyset = excel_data.keySet();
int rownum = 0;
for (String key : keyset) { //loop through the data and add them to the cell
Row row = sheet.createRow(rownum++);
Object [] objArr = excel_data.get(key);
int cellnum = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellnum++);
if(obj instanceof Double)
cell.setCellValue((Double)obj);
else
cell.setCellValue((String)obj);
}
}
/* Write XLS converted CSV file to the output file */
FileOutputStream output_file = new FileOutputStream(new File("CSV2XLS.xls")); //create XLS file
new_workbook.write(output_file);//write converted XLS file to output stream
output_file.close(); //close the file
}

这是因为您只添加了两个列值

excel_data.put(Integer.toString(lnNum), new Object[] {nextLine[0],nextLine[1]});                        

1.无需Object[]- 您可以声明持有String[]

,如CSVReader.readNext返回
excel_data.put(Integer.toString(lnNum), nextLine);

2.As@gagan Singh在评论中正确指出的那样,使用HashMap将失去广告顺序。您可以在从 CSV 读取时直接创建 Excel 单元格值。如果您仍想使用地图,请使用LinkedHashMap,因为这会保留广告顺序。

另外,我看到您在创建 excel 单元格时正在检查obj instanceof Double。CSVParser将所有值视为字符串,因此这不可能是真的。

代码可以简化为这样的东西。

String inputCSVFile = "csv_2_xls.csv";
CSVReader reader = new CSVReader(new FileReader(inputCSVFile));
HSSFWorkbook new_workbook = new HSSFWorkbook();
HSSFSheet sheet = new_workbook.createSheet("CSV2XLS");
int rownum = 0;
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
Row row = sheet.createRow(rownum++);
int cellnum = 0;
for (String value : nextLine) {
Cell cell = row.createCell(cellnum++);
cell.setCellValue(value);
}
}

最新更新