使用java写一段导出excel的代码
时间: 2023-06-07 14:09:16 浏览: 41
好的,以下为Java导出Excel的代码:
```java
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
public class ExcelExport {
public static void main(String[] args) {
try {
// Create a workbook with a sheet
Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet("MySheet");
// Create a row and put some cells in it
Row row = sheet.createRow(0);
Cell cell1 = row.createCell(0, CellType.STRING);
cell1.setCellValue("Name");
Cell cell2 = row.createCell(1, CellType.STRING);
cell2.setCellValue("Age");
// Create some data rows
row = sheet.createRow(1);
cell1 = row.createCell(0, CellType.STRING);
cell1.setCellValue("John");
cell2 = row.createCell(1, CellType.NUMERIC);
cell2.setCellValue(25);
row = sheet.createRow(2);
cell1 = row.createCell(0, CellType.STRING);
cell1.setCellValue("Mary");
cell2 = row.createCell(1, CellType.NUMERIC);
cell2.setCellValue(30);
row = sheet.createRow(3);
cell1 = row.createCell(0, CellType.STRING);
cell1.setCellValue("Dave");
cell2 = row.createCell(1, CellType.NUMERIC);
cell2.setCellValue(40);
// Save the workbook to an Excel file
FileOutputStream fileOut = new FileOutputStream("MyExcelFile.xls");
wb.write(fileOut);
fileOut.close();
wb.close();
System.out.println("Export successful!");
} catch (IOException e) {
System.out.println("Export failed!");
e.printStackTrace();
}
}
}
```
这是一个基本的导出Excel文件的代码,你可以根据你的需求修改数据和文件路径。