用java写一个到处excel工具类
时间: 2023-08-04 18:12:17 浏览: 92
java实现一个配置简单功能强大的excel工具类,搞定大多数excel文件导入导出
以下是一个Java实现的导出Excel工具类的示例:
```java
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelExportUtil {
public static void exportToExcel(List<Object[]> data, String[] headers, String sheetName, String fileName) {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet(sheetName);
int rowNumber = 0;
Row headerRow = sheet.createRow(rowNumber++);
for (int i = 0; i < headers.length; i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(headers[i]);
}
for (Object[] rowData : data) {
Row row = sheet.createRow(rowNumber++);
for (int i = 0; i < rowData.length; i++) {
Cell cell = row.createCell(i);
cell.setCellValue(rowData[i].toString());
}
}
try {
FileOutputStream outputStream = new FileOutputStream(fileName);
workbook.write(outputStream);
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
该工具类使用了Apache POI库,可以将数据导出到Excel文件中。使用示例:
```java
public class Example {
public static void main(String[] args) {
List<Object[]> data = new ArrayList<>();
data.add(new Object[] { "John", "Doe", "Male", 30 });
data.add(new Object[] { "Jane", "Doe", "Female", 25 });
data.add(new Object[] { "Bob", "Smith", "Male", 45 });
String[] headers = { "First Name", "Last Name", "Gender", "Age" };
ExcelExportUtil.exportToExcel(data, headers, "Sheet1", "example.xlsx");
}
}
```
该示例将一个包含3个人员信息的列表导出到名为"example.xlsx"的Excel文件中。
阅读全文