Java导出excel工具类
时间: 2023-08-29 22:10:18 浏览: 115
java导出Excel工具类,
以下是一个简单的Java导出Excel的工具类示例,使用Apache POI库:
```
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.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
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 ExcelUtil {
public static void exportDataToExcel(List<MyData> dataList, String filePath) throws IOException {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Data Sheet");
createHeaderRow(sheet);
int rowCount = 1;
for (MyData data : dataList) {
Row row = sheet.createRow(rowCount++);
writeDataToRow(data, row);
}
autosizeColumns(sheet);
try (FileOutputStream outputStream = new FileOutputStream(filePath)) {
workbook.write(outputStream);
}
}
private static void createHeaderRow(Sheet sheet) {
Row headerRow = sheet.createRow(0);
CellStyle headerCellStyle = sheet.getWorkbook().createCellStyle();
headerCellStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
headerCellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
String[] headers = {"ID", "Name", "Age", "Gender"};
for (int i = 0; i < headers.length; i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(headers[i]);
cell.setCellStyle(headerCellStyle);
}
}
private static void writeDataToRow(MyData data, Row row) {
Cell idCell = row.createCell(0);
idCell.setCellValue(data.getId());
Cell nameCell = row.createCell(1);
nameCell.setCellValue(data.getName());
Cell ageCell = row.createCell(2);
ageCell.setCellValue(data.getAge());
Cell genderCell = row.createCell(3);
genderCell.setCellValue(data.getGender());
}
private static void autosizeColumns(Sheet sheet) {
for (int i = 0; i < sheet.getRow(0).getLastCellNum(); i++) {
sheet.autoSizeColumn(i);
}
}
}
```
在上面的代码中,我们首先创建一个XSSFWorkbook对象,然后创建一个名为“Data Sheet”的工作表。接下来,我们在工作表中创建一个标题行,并设置单元格样式。然后,我们遍历数据列表并将数据写入每一行。最后,我们自适应每列的宽度,然后将工作簿写入输出流中保存到指定路径。
阅读全文