easyexcell3.1.2导出
时间: 2024-03-12 17:40:27 浏览: 98
easy-excel导入导出
以下是使用EasyExcel 3.1.2版本进行导出的示例代码:
```java
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
@Controller
@RequestMapping("/export")
public class EasyExcelExportController {
@GetMapping("/excel")
@ResponseBody
public void exportExcel(HttpServletResponse response) throws IOException {
// 创建数据列表
List<Student> studentList = new ArrayList<>();
studentList.add(new Student("张三", 18, "男"));
studentList.add(new Student("李四", 20, "女"));
studentList.add(new Student("王五", 22, "男"));
// 设置响应头
response.setContentType("application/vnd.ms-excel"); response.setCharacterEncoding("utf-8");
String fileName = URLEncoder.encode("学生信息表", "UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
// 创建Excel写入器
ExcelWriterBuilder writerBuilder = EasyExcel.write(response.getOutputStream(), Student.class);
// 创建工作簿
WriteWorkbook writeWorkbook = writerBuilder.build();
// 创建工作表
ExcelWriterSheetBuilder sheetBuilder = writerBuilder.sheet();
WriteSheet writeSheet = sheetBuilder.build();
// 写入数据
writerBuilder.registerWriteHandler(new CustomCellWriteHandler()); // 自定义单元格写入处理器
writerBuilder.sheet().doWrite(studentList);
// 完成写入并关闭资源
writeWorkbook.finish();
}
}
```
请注意,上述代码中的`Student`类是一个自定义的实体类,用于表示学生信息。`CustomCellWriteHandler`是一个自定义的单元格写入处理器,您可以根据需要进行自定义。
阅读全文