CsvWorkbook java 初始化
时间: 2023-10-16 22:08:49 浏览: 111
以下是CsvWorkbook Java初始化的示例代码:
```java
import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;
import org.apache.poi.ss.usermodel.*;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
public class CsvWorkbook {
private final Workbook workbook;
public CsvWorkbook(File file) throws IOException {
workbook = WorkbookFactory.create(file);
}
public CsvWorkbook(String filePath) throws IOException {
this(new File(filePath));
}
public void addSheet(String sheetName, List<String[]> data) {
Sheet sheet = workbook.createSheet(sheetName);
int rowNum = 0;
for (String[] rowData : data) {
Row row = sheet.createRow(rowNum++);
int colNum = 0;
for (String cellData : rowData) {
Cell cell = row.createCell(colNum++);
cell.setCellValue(cellData);
}
}
}
public void save(File file) throws IOException {
workbook.write(file);
workbook.close();
}
public static void main(String[] args) throws IOException {
String filePath = "/path/to/csv/file.csv";
CsvWorkbook workbook = new CsvWorkbook(filePath);
CSVReader csvReader = new CSVReaderBuilder(new FileReader(filePath)).withSkipLines(1).build();
List<String[]> data = csvReader.readAll();
csvReader.close();
workbook.addSheet("Sheet1", data);
workbook.save(new File("/path/to/excel/file.xlsx"));
}
}
```
这个类使用了Apache POI和OpenCSV库。它可以从CSV文件中读取数据,并将其写入Excel文件中。要使用它,请将文件路径传递给构造函数,并调用`addSheet`方法来添加一个新的工作表。最后,调用`save`方法将Excel文件保存到指定的位置。
阅读全文