java SpringMVC中 POI读取数据库数据并写入Excel表格中,并实现下载功能

18 篇文章 0 订阅
14 篇文章 0 订阅
package cn.itcast.jk.controller.cargo.outproduct;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
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.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.itcast.jk.controller.BaseController;
import cn.itcast.jk.service.OutProductService;
import cn.itcast.jk.vo.OutProductVO;
import cn.itcast.util.DownloadUtil;

/**
 * @Description:
 * @Author: nutony
 * @Company:    http://java.itcast.cn
 * @CreateDate: 2014年10月14日
 */
@Controller
public class OutProductController extends BaseController {
    @Resource
    OutProductService outProductService;

    //转向编辑页面
    @RequestMapping("/cargo/outproduct/toedit.action")
    public String toedit(){
        return "/cargo/outproduct/jOutProduct.jsp";
    }

    @RequestMapping("/cargo/outproduct/printNotemplate.action")
    public void printNotemplate(String inputDate) throws IOException{

        /*
         * POI实现excel打印
         * 1、大标题,合并单元格
         * 2、标题,修饰
         * 3、内容,修饰
         * 
         */

        Workbook wb = new HSSFWorkbook();       //创建一个工作簿
        Sheet sheet = wb.createSheet();         //创建一个工作表
        Row nRow = null;
        Cell nCell = null;
        int rowNo = 0;                          //行号
        int colNo = 1;                          //列号

        //创建样式和字体对象
        CellStyle curStyle = wb.createCellStyle();
        Font curFont = wb.createFont();

        sheet.setColumnWidth(0, 1*278);             //设置列宽 256,BUG,精度不够,总是差一点
        sheet.setColumnWidth(1, 26*278);


        //处理大标题 sheet.addMergedRegion(new CellRangeAddress(开始行,结束行,开始列,结束列));
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 1, 8));        //合并单元格
        nRow = sheet.createRow(rowNo++);
        nRow.setHeightInPoints(36);

        nCell = nRow.createCell(1);
        nCell.setCellStyle(bigTitleStyle(wb));

        nCell.setCellValue(inputDate.replaceFirst("-0", "-").replaceFirst("-", "年") + "月份出货表");     //yyyy-MM

        //处理标题
        String[] title = new String[]{"客户","订单号","货号","数量","工厂","工厂交期","船期","贸易条款"};    //标题数组
        nRow = sheet.createRow(rowNo++);
        nRow.setHeightInPoints(26);

        for(int i=0;i<title.length;i++){
            nCell = nRow.createCell(i+1);
            nCell.setCellValue(title[i]);
            nCell.setCellStyle(this.titleStyle(wb));
        }

        //处理内容
        List<OutProductVO> dataList = outProductService.find(inputDate);
        for(int j=0;j<dataList.size();j++){
            colNo = 1;              //初始化
            OutProductVO op = dataList.get(j);

            nRow = sheet.createRow(rowNo++);
            nRow.setHeightInPoints(24);

            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getCustomName());
            nCell.setCellStyle(this.textStyle(wb, curStyle, curFont));

            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getContractNo());
            nCell.setCellStyle(this.textStyle(wb, curStyle, curFont));

            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getProductNo());
            nCell.setCellStyle(this.textStyle(wb, curStyle, curFont));

            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getCnumber());
            nCell.setCellStyle(this.textStyle(wb, curStyle, curFont));

            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getFactoryName());
            nCell.setCellStyle(this.textStyle(wb, curStyle, curFont));

            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getDeliveryPeriod());
            nCell.setCellStyle(this.textStyle(wb, curStyle, curFont));

            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getShipTime());
            nCell.setCellStyle(this.textStyle(wb, curStyle, curFont));

            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getTradeTerms());
            nCell.setCellStyle(this.textStyle(wb, curStyle, curFont));
        }

        OutputStream os = new FileOutputStream("c:\\outproduct.xls");
        wb.write(os);

        os.flush();
        os.close();
    }

    //模板开发
    @RequestMapping("/cargo/outproduct/printHSSF.action")
    public void printHSSF(String inputDate, HttpServletRequest request, HttpServletResponse response) throws IOException{
        //linux下jdk1.8 方法获取时,不会拼接自己写的目录 
        String path = request.getSession().getServletContext().getRealPath("/") + "/make/xlsprint/";
        InputStream is = new FileInputStream(new File(path + "tOUTPRODUCT.xls"));

        Workbook wb = new HSSFWorkbook(is);     //打开一个模板文件,工作簿
        Sheet sheet = wb.getSheetAt(0);         //获取到第一个工作表

        Row nRow = null;
        Cell nCell = null;
        int rowNo = 0;                          //行号
        int colNo = 1;                          //列号

        //获取模板上的单元格样式
        nRow = sheet.getRow(2);

        //客户的样式
        nCell = nRow.getCell(1);
        CellStyle customStyle = nCell.getCellStyle();       

        //订单号的样式
        nCell = nRow.getCell(2);
        CellStyle contractNoStyle = nCell.getCellStyle();       

        //货号的样式
        nCell = nRow.getCell(3);
        CellStyle productNoStyle = nCell.getCellStyle();        

        //数量的样式
        nCell = nRow.getCell(4);
        CellStyle numStyle = nCell.getCellStyle();      

        //生产厂家的样式
        nCell = nRow.getCell(5);
        CellStyle factoryStyle = nCell.getCellStyle();      

        //日期的样式
        nCell = nRow.getCell(6);
        CellStyle dateStyle = nCell.getCellStyle();     

        //贸易条款的样式
        nCell = nRow.getCell(8);
        CellStyle tradeStyle = nCell.getCellStyle();        


        //处理大标题
        nRow = sheet.getRow(rowNo++);           //获取一个行对象
        nCell = nRow.getCell(colNo);            //获取一个单元格对象
        nCell.setCellValue(inputDate.replaceFirst("-0", "-").replaceFirst("-", "年") + "月份出货表");     //yyyy-MM

        rowNo++;                                //跳过静态表格头

        //处理内容
        List<OutProductVO> dataList = outProductService.find(inputDate);
        for(int j=0;j<dataList.size();j++){
            colNo = 1;              //初始化
            OutProductVO op = dataList.get(j);

            nRow = sheet.createRow(rowNo++);
            nRow.setHeightInPoints(24);

            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getCustomName());
            nCell.setCellStyle(customStyle);

            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getContractNo());
            nCell.setCellStyle(contractNoStyle);

            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getProductNo());
            nCell.setCellStyle(productNoStyle);

            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getCnumber());
            nCell.setCellStyle(numStyle);

            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getFactoryName());
            nCell.setCellStyle(factoryStyle);

            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getDeliveryPeriod());
            nCell.setCellStyle(dateStyle);

            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getShipTime());
            nCell.setCellStyle(dateStyle);

            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getTradeTerms());
            nCell.setCellStyle(tradeStyle);
        }

//      OutputStream os = new FileOutputStream("c:\\outproduct.xls");
//      wb.write(os);
//      
//      os.flush();
//      os.close();

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        wb.write(os);

        DownloadUtil downloadUtil = new DownloadUtil();             //直接弹出下载框,用户可以打开,可以保存
        downloadUtil.download(os, response, "出货表.xls");

        os.flush();
        os.close();
    }

    //模板开发XSSF
    @RequestMapping("/cargo/outproduct/print.action")
    public void print(String inputDate, HttpServletRequest request, HttpServletResponse response) throws IOException{
        //linux下jdk1.8 方法获取时,不会拼接自己写的目录 
        String path = request.getSession().getServletContext().getRealPath("/") + "/make/xlsprint/";
        InputStream is = new FileInputStream(new File(path + "tOUTPRODUCT.xlsx"));

        Workbook wb = new XSSFWorkbook(is);     //打开一个模板文件,工作簿 2007以上版本
        Sheet sheet = wb.getSheetAt(0);         //获取到第一个工作表

        Row nRow = null;
        Cell nCell = null;
        int rowNo = 0;                          //行号
        int colNo = 1;                          //列号

        //获取模板上的单元格样式
        nRow = sheet.getRow(2);

        //客户的样式
        nCell = nRow.getCell(1);
        CellStyle customStyle = nCell.getCellStyle();       

        //订单号的样式
        nCell = nRow.getCell(2);
        CellStyle contractNoStyle = nCell.getCellStyle();       

        //货号的样式
        nCell = nRow.getCell(3);
        CellStyle productNoStyle = nCell.getCellStyle();        

        //数量的样式
        nCell = nRow.getCell(4);
        CellStyle numStyle = nCell.getCellStyle();      

        //生产厂家的样式
        nCell = nRow.getCell(5);
        CellStyle factoryStyle = nCell.getCellStyle();      

        //日期的样式
        nCell = nRow.getCell(6);
        CellStyle dateStyle = nCell.getCellStyle();     

        //贸易条款的样式
        nCell = nRow.getCell(8);
        CellStyle tradeStyle = nCell.getCellStyle();        


        //处理大标题
        nRow = sheet.getRow(rowNo++);           //获取一个行对象
        nCell = nRow.getCell(colNo);            //获取一个单元格对象
        nCell.setCellValue(inputDate.replaceFirst("-0", "-").replaceFirst("-", "年") + "月份出货表");     //yyyy-MM

        rowNo++;                                //跳过静态表格头

        //处理内容
        List<OutProductVO> dataList = outProductService.find(inputDate);
        for(int j=0;j<dataList.size();j++){
            colNo = 1;              //初始化
            OutProductVO op = dataList.get(j);

            nRow = sheet.createRow(rowNo++);
            nRow.setHeightInPoints(24);

            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getCustomName());
            nCell.setCellStyle(customStyle);

            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getContractNo());
            nCell.setCellStyle(contractNoStyle);

            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getProductNo());
            nCell.setCellStyle(productNoStyle);

            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getCnumber());
            nCell.setCellStyle(numStyle);

            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getFactoryName());
            nCell.setCellStyle(factoryStyle);

            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getDeliveryPeriod());
            nCell.setCellStyle(dateStyle);

            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getShipTime());
            nCell.setCellStyle(dateStyle);

            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getTradeTerms());
            nCell.setCellStyle(tradeStyle);
        }

//      OutputStream os = new FileOutputStream("c:\\outproduct.xls");
//      wb.write(os);
//      
//      os.flush();
//      os.close();

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        wb.write(os);

        DownloadUtil downloadUtil = new DownloadUtil();             //直接弹出下载框,用户可以打开,可以保存
        downloadUtil.download(os, response, "出货表.xlsx");

        os.flush();
        os.close();
    }

    //大标题样式
    private CellStyle bigTitleStyle(Workbook wb){
        CellStyle curStyle = wb.createCellStyle();
        Font curFont = wb.createFont();

        curFont.setFontName("宋体");
        curFont.setFontHeightInPoints((short)16);
        curFont.setBoldweight(Font.BOLDWEIGHT_BOLD);                    //字体加粗

        curStyle.setFont(curFont);                                      //绑定字体

        curStyle.setAlignment(CellStyle.ALIGN_CENTER);                  //横向居中
        curStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);       //纵向居中

        return curStyle;
    }

    //小标题样式
    private CellStyle titleStyle(Workbook wb){
        CellStyle curStyle = wb.createCellStyle();
        Font curFont = wb.createFont();

        curFont.setFontName("黑体");
        curFont.setFontHeightInPoints((short)12);

        curStyle.setFont(curFont);                                      //绑定字体

        curStyle.setAlignment(CellStyle.ALIGN_CENTER);                  //横向居中
        curStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);       //纵向居中


        curStyle.setBorderTop(CellStyle.BORDER_THIN);                   //设置四周边线,细线
        curStyle.setBorderBottom(CellStyle.BORDER_THIN);
        curStyle.setBorderLeft(CellStyle.BORDER_THIN);
        curStyle.setBorderRight(CellStyle.BORDER_THIN);

        return curStyle;
    }

    //文字样式
    private CellStyle textStyle(Workbook wb, CellStyle curStyle, Font curFont){

        curFont.setFontName("Times New Roman");
        curFont.setFontHeightInPoints((short)10);

        curStyle.setFont(curFont);                                      //绑定字体

        curStyle.setAlignment(CellStyle.ALIGN_LEFT);                    //横向居左
        curStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);       //纵向居中


        curStyle.setBorderTop(CellStyle.BORDER_THIN);                   //设置四周边线,细线
        curStyle.setBorderBottom(CellStyle.BORDER_THIN);
        curStyle.setBorderLeft(CellStyle.BORDER_THIN);
        curStyle.setBorderRight(CellStyle.BORDER_THIN);

        return curStyle;
    }
}

文件下载类

package cn.itcast.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

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

public class DownloadUtil {

    /**
     * @param filePath 要下载的文件路径
     * @param returnName 返回的文件名
     * @param response HttpServletResponse
     * @param delFlag 是否删除文件
     */
    protected void download(String filePath,String returnName,HttpServletResponse response,boolean delFlag){
        this.prototypeDownload(new File(filePath), returnName, response, delFlag);
    }


    /**
     * @param file 要下载的文件
     * @param returnName 返回的文件名
     * @param response HttpServletResponse
     * @param delFlag 是否删除文件
     */
    protected void download(File file,String returnName,HttpServletResponse response,boolean delFlag){
        this.prototypeDownload(file, returnName, response, delFlag);
    }

    /**
     * @param file 要下载的文件
     * @param returnName 返回的文件名
     * @param response HttpServletResponse
     * @param delFlag 是否删除文件
     */
    public void prototypeDownload(File file,String returnName,HttpServletResponse response,boolean delFlag){
        // 下载文件
        FileInputStream inputStream = null;
        ServletOutputStream outputStream = null;
        try {
            if(!file.exists()) return;
            response.reset();
            //设置响应类型    PDF文件为"application/pdf",WORD文件为:"application/msword", EXCEL文件为:"application/vnd.ms-excel"。  
            response.setContentType("application/octet-stream;charset=utf-8");

            //设置响应的文件名称,并转换成中文编码
            //returnName = URLEncoder.encode(returnName,"UTF-8");
            returnName = response.encodeURL(new String(returnName.getBytes(),"iso8859-1")); //保存的文件名,必须和页面编码一致,否则乱码

            //attachment作为附件下载;inline客户端机器有安装匹配程序,则直接打开;注意改变配置,清除缓存,否则可能不能看到效果
            response.addHeader("Content-Disposition",   "attachment;filename="+returnName);  

            //将文件读入响应流
            inputStream = new FileInputStream(file);
            outputStream = response.getOutputStream();
            int length = 1024;
            int readLength=0;
            byte buf[] = new byte[1024];
            readLength = inputStream.read(buf, 0, length);
            while (readLength != -1) {
                outputStream.write(buf, 0, readLength);
                readLength = inputStream.read(buf, 0, length);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //删除原文件

            if(delFlag) {               
                file.delete();
            }
        }
    }

    /**
     * by tony 2013-10-17
     * @param byteArrayOutputStream 将文件内容写入ByteArrayOutputStream
     * @param response HttpServletResponse  写入response
     * @param returnName 返回的文件名
     */
    public void download(ByteArrayOutputStream byteArrayOutputStream, HttpServletResponse response, String returnName) throws IOException{
        response.setContentType("application/octet-stream;charset=utf-8");
        returnName = response.encodeURL(new String(returnName.getBytes(),"iso8859-1"));         //保存的文件名,必须和页面编码一致,否则乱码
        response.addHeader("Content-Disposition",   "attachment;filename=" + returnName);  
        response.setContentLength(byteArrayOutputStream.size());

        ServletOutputStream outputstream = response.getOutputStream();  //取得输出流
        byteArrayOutputStream.writeTo(outputstream);                    //写到输出流
        byteArrayOutputStream.close();                                  //关闭
        outputstream.flush();                                           //刷数据
    }
}
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
poi解析excel功能参数说明 此项目是基于springMVC实现的,基本流程为从前台jsp页面使用Ajax文件上传导入excel文件(.xls(97-03)/.xlsx(07以后)),传到后台controller调用相应工具类解析后返回指定参数做后续处理. 1. POIUtil.java工具类 解析通过MutilpartFile导入的Excel并解析里面数据,先判断文件的类型(excel处理有两种此处为两种通用)是.xls/.xlsx,通过workbook.getNumberOfSheets()获取工作簿数量,遍历工作簿,sheet.getLastRowNum()获取最大行数,将每行数据放入List list = new Array List(),并根据excel数据类型将器转换为字符串、数字、Boolean、公式、空值类型防止出现错误,最后返回一个list. 2. ExcelUtil.java工具类 解析通过MutilpartFile导入的Excel并解析里面数据,先判断文件的类型(excel处理有两种此处为两种通用)是.xls/.xlsx,采用Apache的POI的API来操作Excel读取内容后保存List,再将List转Json(使用Linked,增删快,与Excel表顺序保持一致),Sheet表1————>List1<Map> 步骤1:根据Excel版本类型创建对于的Workbook以及CellSytle 步骤2:遍历每一个表的每一行的每一列,这里做了些小改动,因为后续可能解析过后可能会保存数据库,这里为第一行数据添加一个自定义表头 String[] p = new String[]{"name","age","sex","tel","address","e-mail","phone"}; 遍历的列数量以p的length为准 步骤3:一个sheet表就是一个Json,多表就多Json,对应一个 List 一个sheet表的一行数据就是一个 Map 一行的一列,就把当前列头为key,列值为value存到该列的Map Map 一个线性Hash Map,以Excel的sheet表顺序,并以sheet表明作为key,sheet表转换Json后的字符串作为value 最后返回一个LinkedHashMap 3. ExcelToJsonPoi.java工具类 这个与上面工具类类似,不过这个是解析本地excel文件不是使用的流,使用迭代遍历sheet工作簿与每行每列的值,将所有类型作为String类型处理返回一个json对象输出至控制台
Java使用Spring MVC实现数据库备份可以通过以下步骤实现: 1. 配置数据库连接信息:在Spring MVC的配置文件,配置数据库的连接信息,包括数据库的URL、用户名和密码。 2. 创建备份文件夹:在服务器上创建一个用于存储数据库备份文件的文件夹。 3. 编写备份方法:在Spring MVC的控制器,编写一个备份数据库的方法。可以使用Java的Runtime类来执行命令行操作,调用数据库的备份命令将数据库备份到指定的文件夹。 4. 编写恢复方法:同样在控制器,编写一个恢复数据库的方法。通过调用数据库的恢复命令,将备份文件数据还原到数据库。 5. 配置路由:在Spring MVC的配置文件,配置备份和恢复方法的路由信息,使其可以通过URL访问到。 下面是一个示例代码: ```java @Controller @RequestMapping("/database") public class DatabaseController { @RequestMapping("/backup") public void backupDatabase() { try { // 创建备份文件夹 File backupFolder = new File("/path/to/backup/folder"); if (!backupFolder.exists()) { backupFolder.mkdirs(); } // 执行备份命令 String command = "mysqldump -u username -p password database > /path/to/backup/folder/backup.sql"; Process process = Runtime.getRuntime().exec(command); int exitValue = process.waitFor(); if (exitValue == 0) { System.out.println("Database backup successful."); } else { System.out.println("Database backup failed."); } } catch (Exception e) { e.printStackTrace(); } } @RequestMapping("/restore") public void restoreDatabase() { try { // 执行恢复命令 String command = "mysql -u username -p password database < /path/to/backup/folder/backup.sql"; Process process = Runtime.getRuntime().exec(command); int exitValue = process.waitFor(); if (exitValue == 0) { System.out.println("Database restore successful."); } else { System.out.println("Database restore failed."); } } catch (Exception e) { e.printStackTrace(); } } } ``` 请注意,上述代码的`/path/to/backup/folder`应替换为实际的备份文件夹路径,`username`、`password`和`database`应替换为实际的数据库连接信息。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值