【英文】Java将CSV文件转换为Excel文件

Preface

Java converts CSV files to Excel files

Preparation

Source Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com;

import com.spire.xls.*;

import java.util.EnumSet;

public class Tools {
/**
* Convert CSV file to Excel file
* @param dir Directory: `/home/`, `C:/Users/`
* @param filename File name: `filename`
*/
public static void convertCsvToExcel(String dir, String filename) {
// Load the CSV file
Workbook workbook = new Workbook();
workbook.loadFromFile(dir + filename + ".csv", ",", 1, 1);
// Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
// Access the used range in the worksheet
CellRange usedRange = sheet.getAllocatedRange();
// Ignore errors when saving numbers in the range as text
usedRange.setIgnoreErrorOptions(EnumSet.of(IgnoreErrorType.NumberAsText));
// Adjust row height and column width automatically
usedRange.autoFitColumns();
usedRange.autoFitRows();
// Save the document
workbook.saveToFile(dir + filename + ".xlsx", ExcelVersion.Version2013);
}
}

Completion

References

CSDN——Eiceblue