springboot读取excel文件模板写入数据,并下载

4 篇文章 0 订阅

先定好excel头部内容,样式等,以此为模板,插入表格数据,就不用HSSFCellStyle类设置样式了。
例如:
在这里插入图片描述
前4行内容是不变的,从第五行开始 从数据库拿出数据 写入表格
完成后
在这里插入图片描述pom.xml,必要两个依赖

		<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.14</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17-beta1</version>
        </dependency>

controller

import com.tyxx.common.enums.HttpStatusEnum;
import com.tyxx.common.render.makeResult;
import com.tyxx.model.Jzzhxx;
import com.tyxx.service.JzzhxxService;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;


@Controller     //controller + ResponseBody
@CrossOrigin
@RequestMapping(value = "/download")
public class DownloadController {

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

    @Autowired
    private JzzhxxService jzzhxxService;

    @RequestMapping(value = "/loadFile/{choose}", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public void loadFile(@PathVariable int choose, HttpServletResponse response) throws IOException {
		Resource resource = new ClassPathResource("templates/reporttemplate.xls");
        boolean isFile = resource.isFile();
        if(!isFile){     //如果不存在返回
            return;
        }
        String path = resource.getFile().getPath();     //获取文件路径

        /* 数据写入模板文件中 */
        //更改文件名编码
        String fileName = "基站综合信息.xls";
        String gFileName = URLEncoder.encode(fileName, "UTF-8");
        //如进行下载名为:文件(3).txt,下载时显示名为:文件+(3).txt --空格变为了+号
        //解决办法如下
        String dFileName = gFileName.replaceAll("\\+", "%20");
        InputStream in = null;
        Workbook exl = null;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            in = new FileInputStream(path);
            exl = WorkbookFactory.create(in);
            Sheet sheet1 = exl.getSheetAt(0);
            int rowNums = sheet1.getLastRowNum();	//模板的行数0开始,返回值比行数小1
            short cellNums = sheet1.getRow(3).getLastCellNum();		//列数
            List<Jzzhxx> lt = jzzhxxService.getAllList();
            for (int i = 0, y = lt.size(); i < y; ++i) {
                Row row = sheet1.createRow( i + 4 );
                row.createCell(0).setCellValue(i + 1);  //序号
                row.createCell(1).setCellValue(lt.get(i).getName().trim());     //站名
                row.createCell(2).setCellValue(lt.get(i).getYys().trim());      //运营商
                row.createCell(3).setCellValue(lt.get(i).getJingdu().trim()); //经度
                row.createCell(4).setCellValue(lt.get(i).getWeidu().trim());  //纬度
                row.createCell(5).setCellValue(lt.get(i).getGaodu());                //高度
                row.createCell(6).setCellValue(lt.get(i).getLeibie());                //基站类别
                row.createCell(7).setCellValue(lt.get(i).getType());                //基站类型
                row.createCell(8).setCellValue(lt.get(i).getLianxiren());                //区域联系人
                row.createCell(9).setCellValue(lt.get(i).getFugai());                //覆盖范围
            }
            //激活浏览器弹出窗口
            response.setContentType("application/x-msdownload");
            //浏览器弹出窗口显示的文件名
            response.addHeader("Content-Disposition", "attachment;filename=" + dFileName);
            exl.write(out);
            //in = new ByteArrayInputStream(out.toByteArray());
            response.getOutputStream().write(out.toByteArray());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (exl != null) {
                    exl.close();
                }
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }       
}

项目结构
在这里插入图片描述前台
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值