java导出excel案例
时间: 2023-09-24 16:13:39 浏览: 150
以下是一个简单的Java导出Excel的示例:
1. 首先,需要添加poi和poi-ooxml依赖:
```xml
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
```
2. 创建一个工具类来导出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.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelUtil {
public static void export(List<Object[]> data, String fileName) throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet1");
// 设置表头
XSSFRow headerRow = sheet.createRow(0);
String[] headers = {"Name", "Age", "Gender"};
for (int i = 0; i < headers.length; i++) {
XSSFCell cell = headerRow.createCell(i);
cell.setCellValue(headers[i]);
}
// 填充数据
int rowNum = 1;
for (Object[] row : data) {
XSSFRow dataRow = sheet.createRow(rowNum++);
for (int i = 0; i < row.length; i++) {
XSSFCell cell = dataRow.createCell(i);
cell.setCellValue(row[i].toString());
}
}
// 格式化单元格
XSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setWrapText(true);
for (int i = 0; i < headers.length; i++) {
sheet.autoSizeColumn(i);
sheet.setColumnWidth(i, sheet.getColumnWidth(i) + 500);
for (Row row : sheet) {
Cell cell = row.getCell(i);
if (cell != null) {
cell.setCellStyle(cellStyle);
}
}
}
// 导出Excel
FileOutputStream outputStream = new FileOutputStream(fileName);
workbook.write(outputStream);
outputStream.close();
}
}
```
3. 在主函数中调用导出方法:
```java
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
// 准备数据
List<Object[]> data = new ArrayList<>();
data.add(new Object[]{"Tom", 20, "Male"});
data.add(new Object[]{"Lily", 22, "Female"});
data.add(new Object[]{"Lucy", 21, "Female"});
// 导出Excel
ExcelUtil.export(data, "output.xlsx");
}
}
```
以上示例演示了如何使用Java导出Excel文件。实际上,Excel导出的实现方式还有很多,可以根据具体需求选择合适的方法。
阅读全文
相关推荐












