java操作生成Excel报表

课程设计中遇到需要生成报表,于是在网上搜集了相关资料。下面贴上实现后的代码。


首先,项目是maven项目。添加依赖。

<!-- 输出报表依赖 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.16</version>
        </dependency>

controller:

/*
     * 根据传递的ID导出对应报表
     */
    @RequestMapping("/export/{id}")  
    public void export(HttpServletRequest request, HttpServletResponse response,@PathVariable("id")Integer id) {  
        response.setContentType("application/vnd.ms-excel");  
        response.setHeader("Content-disposition", "attachment;filename=myExcel.xls");  
        OutputStream ouputStream = null;  
        HSSFWorkbook wb = exportData(id);  
        try {  
            ouputStream = response
  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用Apache POI库来生成Excel报表。以下是一个简单的示例代码,可以创建一个包含一些数据的Excel工作簿,并将其保存在本地文件系统上。 ```java import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelGenerator { public static void main(String[] args) throws IOException { Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet("Report"); // 创建表头 Row headerRow = sheet.createRow(0); Cell headerCell1 = headerRow.createCell(0); headerCell1.setCellValue("Name"); Cell headerCell2 = headerRow.createCell(1); headerCell2.setCellValue("Age"); Cell headerCell3 = headerRow.createCell(2); headerCell3.setCellValue("City"); // 创建数据行 Row dataRow = sheet.createRow(1); Cell dataCell1 = dataRow.createCell(0); dataCell1.setCellValue("John"); Cell dataCell2 = dataRow.createCell(1); dataCell2.setCellValue(30); Cell dataCell3 = dataRow.createCell(2); dataCell3.setCellValue("New York"); // 保存工作簿到本地文件系统 FileOutputStream outputStream = new FileOutputStream("report.xlsx"); workbook.write(outputStream); workbook.close(); } } ``` 这个示例代码创建了一个名为“Report”的工作表,并在第一行创建了一个表头。然后,在第二行创建了一行数据。最后,将工作簿保存到名为“report.xlsx”的本地文件中。可以根据需要修改此代码以生成更复杂的Excel报表

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值