javaweb下载excel文件

方案一:使用servlet下载文件,代码写在servlet类中。

maven依赖

<!-- java excel api -->
<dependency>
  <groupId>net.sourceforge.jexcelapi</groupId>
  <artifactId>jxl</artifactId>
  <version>2.6.10</version>
</dependency>

servlet代码如下:

public class ServletTest extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("doGet(HttpServletRequest req, HttpServletResponse resp)");
        OutputStream output = resp.getOutputStream();
        resp.reset();
        resp.setHeader("Content-disposition", "attachment; filename=temp.xls");
        resp.setContentType("application/msexcel");
        // 创建可写入的Excel工作薄,且内容将写入到输出流,并通过输出流输出给客户端浏览
        WritableWorkbook wk = Workbook.createWorkbook(output);
        /// 创建可写入的Excel工作表
        WritableSheet sheet = wk.createSheet("成绩表", 0);

        try {
            // 把单元格(column, row)到单元格(column1, row1)进行合并。
            // mergeCells(column, row, column1, row1);
            sheet.mergeCells(0, 0, 4, 0);// 单元格合并方法

            // 创建WritableFont 字体对象,参数依次表示黑体、字号12、粗体、非斜体、不带下划线、亮蓝色
            WritableFont titleFont = new WritableFont(WritableFont.createFont("黑体"), 12, WritableFont.BOLD, false,
                UnderlineStyle.NO_UNDERLINE, Colour.LIGHT_BLUE);
            // 创建WritableCellFormat对象,将该对象应用于单元格从而设置单元格的样式
            WritableCellFormat titleFormat = new WritableCellFormat();
            // 设置字体格式
            titleFormat.setFont(titleFont);
            // 设置文本水平居中对齐
            titleFormat.setAlignment(Alignment.CENTRE);
            // 设置文本垂直居中对齐
            titleFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
            // 设置背景颜色
            titleFormat.setBackground(Colour.GRAY_25);
            // 设置自动换行
            titleFormat.setWrap(true);

            // 添加Label对象,参数依次表示在第一列,第一行,内容,使用的格式
            Label lab_00 = new Label(0, 0, "学员考试成绩一览表", titleFormat);
            // 将定义好的Label对象添加到工作表上,这样工作表的第一列第一行的内容为‘学员考试成绩一览表’并应用了titleFormat定义的样式
            sheet.addCell(lab_00);
            WritableCellFormat cloumnTitleFormat = new WritableCellFormat();
            cloumnTitleFormat.setFont(new WritableFont(WritableFont.createFont("宋体"), 10, WritableFont.BOLD, false));
            cloumnTitleFormat.setAlignment(Alignment.CENTRE);
            Label lab_01 = new Label(0, 1, "姓名", cloumnTitleFormat);
            Label lab_11 = new Label(1, 1, "班级", cloumnTitleFormat);
            Label lab_21 = new Label(2, 1, "笔试成绩", cloumnTitleFormat);
            Label lab_31 = new Label(3, 1, "上机成绩", cloumnTitleFormat);
            Label lab_41 = new Label(4, 1, "考试日期", cloumnTitleFormat);
            sheet.addCell(lab_01);
            sheet.addCell(lab_11);
            sheet.addCell(lab_21);
            sheet.addCell(lab_31);
            sheet.addCell(lab_41);
            sheet.addCell(new Label(0, 2, "李明"));
            sheet.addCell(new Label(1, 2, "As178"));

            // 定义数字格式

            NumberFormat nf = new NumberFormat("0.00");

            WritableCellFormat wcf = new WritableCellFormat(nf);

            // 类似于Label对象,区别Label表示文本数据,Number表示数值型数据
            Number numlab_22 = new Number(2, 2, 78, wcf);
            sheet.addCell(numlab_22);
            sheet.addCell(new Number(3, 2, 87, new WritableCellFormat(new NumberFormat("#.##"))));
            // 定义日期格式
            DateFormat df = new DateFormat("yyyy-MM-dd hh:mm:ss");
            // 创建WritableCellFormat对象
            WritableCellFormat datewcf = new WritableCellFormat(df);
            // 类似于Label对象,区别Label表示文本数据,DateTime表示日期型数据
            DateTime dtLab_42 = new DateTime(4, 2, new Date(), datewcf);
            sheet.addCell(dtLab_42);
            // 将定义的工作表输出到之前指定的介质中(这里是客户端浏览器)
            wk.write();
            // 操作完成时,关闭对象,释放占用的内存空间
            wk.close();
        } catch (WriteException e) {
            e.printStackTrace();
        }
    }
}

web.xml配置,代码如下,其中com.xxx.ServletTest改成自己的类路径

  <servlet>
    <servlet-name>servletTest</servlet-name>
    <servlet-class>
            com.xxx.ServletTest
        </servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>servletTest</servlet-name>
    <url-pattern>/servletTest</url-pattern>
  </servlet-mapping>

其他配置是基础配置,此不介绍。

在浏览器上直接访问:localhost:8080/aaa/servletTest,即可保存或者下载文件。

其中,aaa改成自己的项目名称

 

方案二:使用controler调用dubbo服务方式,具体细节写在dubbo服务层,但是需要创建文件在本地。

controller层代码:

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.xxx.service.ExportService;

@RestController
@RequestMapping("/ops/export")
public class ExportController {

    private static final Logger logger = Logger.getLogger(ExportController.class);

    @Autowired
    private ExportService exportService;

    /**
     * 导出用户列表
     */
    @RequestMapping("/exportUserList")
    public void exportUserList(@RequestBody Map<String, Object> params, HttpServletRequest req,
            HttpServletResponse resp) {
        logger.info("exportUserList() begin... params=" + JSON.toJSONString(params, true));

        String filePath = exportService.exportUserList(params);
        try {
            InputStream is = new FileInputStream(filePath);
            resp.reset();
            resp.setContentType("bin");
            resp.setContentType("contentType");
            resp.setHeader("Content-disposition",
                "attachment;filename=" + URLEncoder.encode(new File(filePath).getName(), "UTF-8"));

            // 获取绑定了客户端的流
            ServletOutputStream output = resp.getOutputStream();
            // 把输入流中的数据写入到输出流中
            IOUtils.copy(is, output);

            is.close();
        } catch (Exception e) {
            logger.error("exportUserList() Exception: ", e);
        }

        logger.info("exportUserList() end... filePath=" + filePath);
    }
}

实现类代码

@Autowired
    private OpsUserMapper opsUserMapper;

    @Override
    public String exportUserList(Map<String, Object> request) throws Exception {

        String filePath = FileUtils.getFullFilePath("OPS", "xls", "userList");
        logger.info("filePath=" + filePath);

        File file = new File(filePath);
        File parentFile = new File(file.getParent());
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }

        // 创建可写入的Excel工作薄,且内容将写入到输出流,并通过输出流输出给客户端浏览
        WritableWorkbook wk = Workbook.createWorkbook(file);
        /// 创建可写入的Excel工作表
        WritableSheet sheet = wk.createSheet("用户数据", 0);
        WritableCellFormat cloumnTitleFormat = new WritableCellFormat();
        cloumnTitleFormat.setFont(new WritableFont(WritableFont.createFont("宋体"), 10, WritableFont.BOLD, false));
        cloumnTitleFormat.setAlignment(Alignment.LEFT);
        sheet.addCell(new Label(0, 0, "手机号", cloumnTitleFormat));
        sheet.addCell(new Label(1, 0, "注册时间", cloumnTitleFormat));
        int i = 1;
        List<OpsUser> queryUserList = opsUserMapper.queryUserList(request);
        DateFormat dateFormat = new DateFormat(DateUtils.DATE_TIME_PATTERN);
        for (OpsUser each : queryUserList) {
            sheet.addCell(new Label(0, i, each.getPhoneNo()));
            sheet.addCell(new DateTime(1, i, each.getCreateTime(), new WritableCellFormat(dateFormat)));
            i++;
        }
        wk.write();
        wk.close();

        return filePath;
    }

文档内容如下:

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值