SpringMvc 使用poi导入导出Excel

转载自http://webook-java.iteye.com/blog/1699621

下面2个博客也不错,简洁明了

http://www.cnblogs.com/littlecharacter/p/5580676.html

http://blog.csdn.net/onepersontz/article/details/49891405

Util类  
package com.common.util;  
  
public class ExportUtil  
{  
    private XSSFWorkbook wb = null;  
  
    private XSSFSheet sheet = null;  
  
    /** 
     * @param wb 
     * @param sheet 
     */  
    public ExportUtil(XSSFWorkbook wb, XSSFSheet sheet)  
    {  
        this.wb = wb;  
        this.sheet = sheet;  
    }  
  
    /** 
     * 合并单元格后给合并后的单元格加边框 
     *  
     * @param region 
     * @param cs 
     */  
    public void setRegionStyle(CellRangeAddress region, XSSFCellStyle cs)  
    {  
  
        int toprowNum = region.getFirstRow();  
        for (int i = toprowNum; i <= region.getLastRow(); i++)  
        {  
            XSSFRow row = sheet.getRow(i);  
            for (int j = region.getFirstColumn(); j <= region.getLastColumn(); j++)  
            {  
                XSSFCell cell = row.getCell(j);// XSSFCellUtil.getCell(row,  
                                                // (short) j);  
                cell.setCellStyle(cs);  
            }  
        }  
    }  
  
    /** 
     * 设置表头的单元格样式 
     *  
     * @return 
     */  
    public XSSFCellStyle getHeadStyle()  
    {  
        // 创建单元格样式  
        XSSFCellStyle cellStyle = wb.createCellStyle();  
        // 设置单元格的背景颜色为淡蓝色  
        cellStyle.setFillForegroundColor(HSSFColor.PALE_BLUE.index);  
        cellStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);  
        // 设置单元格居中对齐  
        cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);  
        // 设置单元格垂直居中对齐  
        cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);  
        // 创建单元格内容显示不下时自动换行  
        cellStyle.setWrapText(true);  
        // 设置单元格字体样式  
        XSSFFont font = wb.createFont();  
        // 设置字体加粗  
        font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);  
        font.setFontName("宋体");  
        font.setFontHeight((short) 200);  
        cellStyle.setFont(font);  
        // 设置单元格边框为细线条  
        cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);  
        cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);  
        cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);  
        cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);  
        return cellStyle;  
    }  
  
    /** 
     * 设置表体的单元格样式 
     *  
     * @return 
     */  
    public XSSFCellStyle getBodyStyle()  
    {  
        // 创建单元格样式  
        XSSFCellStyle cellStyle = wb.createCellStyle();  
        // 设置单元格居中对齐  
        cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);  
        // 设置单元格垂直居中对齐  
        cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);  
        // 创建单元格内容显示不下时自动换行  
        cellStyle.setWrapText(true);  
        // 设置单元格字体样式  
        XSSFFont font = wb.createFont();  
        // 设置字体加粗  
        font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);  
        font.setFontName("宋体");  
        font.setFontHeight((short) 200);  
        cellStyle.setFont(font);  
        // 设置单元格边框为细线条  
        cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);  
        cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);  
        cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);  
        cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);  
        return cellStyle;  
    }  
}  
service类  
public interface ITestExportExcelService  
{  
    public void exportExcel(String hql,String [] titles,ServletOutputStream outputStream);  
}  
@Service  
public class TestExportExcelServiceImpl implements ITestExportExcelService  
{  
    @Resource  
    private ITestExportExcelDao dao;  
      
    public void exportExcel(String hql, String[] titles, ServletOutputStream outputStream)  
    {  
        List<Goods> list = dao.exportExcel(hql);  
        // 创建一个workbook 对应一个excel应用文件  
        XSSFWorkbook workBook = new XSSFWorkbook();  
        // 在workbook中添加一个sheet,对应Excel文件中的sheet  
        XSSFSheet sheet = workBook.createSheet("导出excel例子");  
        ExportUtil exportUtil = new ExportUtil(workBook, sheet);  
        XSSFCellStyle headStyle = exportUtil.getHeadStyle();  
        XSSFCellStyle bodyStyle = exportUtil.getBodyStyle();  
        // 构建表头  
        XSSFRow headRow = sheet.createRow(0);  
        XSSFCell cell = null;  
        for (int i = 0; i < titles.length; i++)  
        {  
            cell = headRow.createCell(i);  
            cell.setCellStyle(headStyle);  
            cell.setCellValue(titles[i]);  
        }  
        // 构建表体数据  
        if (list != null && list.size() > 0)  
        {  
            for (int j = 0; j < list.size(); j++)  
            {  
                XSSFRow bodyRow = sheet.createRow(j + 1);  
                Goods goods = list.get(j);  
  
                cell = bodyRow.createCell(0);  
                cell.setCellStyle(bodyStyle);  
                cell.setCellValue(goods.getGoodsName());  
  
                cell = bodyRow.createCell(1);  
                cell.setCellStyle(bodyStyle);  
                cell.setCellValue(goods.getGoodsCost());  
  
                cell = bodyRow.createCell(2);  
                cell.setCellStyle(bodyStyle);  
                cell.setCellValue(goods.getGoodsUnit());  
            }  
        }  
        try  
        {  
            workBook.write(outputStream);  
            outputStream.flush();  
            outputStream.close();  
        }  
        catch (IOException e)  
        {  
            e.printStackTrace();  
        }  
        finally  
        {  
            try  
            {  
                outputStream.close();  
            }  
            catch (IOException e)  
            {  
                e.printStackTrace();  
            }  
        }  
  
    }  
  
}  
dao类  
public interface ITestExportExcelDao  
{  
    public List<Goods> exportExcel(String hql);  
}  
@Repository  
public class TestExportExcelDaoImpl implements ITestExportExcelDao  
{  
    @Resource  
    private SessionFactory factory;  
      
    /** 
     * 以goods表为例导出测试 
     */  
    @SuppressWarnings("unchecked")  
    public List<Goods> exportExcel(String hql)  
    {  
        Session session = factory.getCurrentSession();  
        List<Goods> list = session.createQuery(hql).list();  
        return list;  
    }  
  
}  
控制层Controller  
@Controller  
@RequestMapping("/testexportexcel/*")  
public class TestExportExcelController  
{  
    @Resource  
    private ITestExportExcelService service;  
  
    @RequestMapping  
    public String exportExcel(HttpServletResponse response)  
    {  
        response.setContentType("application/binary;charset=ISO8859_1");  
        try  
        {  
            ServletOutputStream outputStream = response.getOutputStream();  
            String fileName = new String(("导出excel例子").getBytes(), "ISO8859_1");  
            response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xlsx");// 组装附件名称和格式  
            String hql = "from Goods";  
            String[] titles = { "商品名", "商品单价", "商品单位" };  
            service.exportExcel(hql, titles, outputStream);  
        }  
        catch (IOException e)  
        {  
            e.printStackTrace();  
        }  
        return null;  
    }  
  
    @RequestMapping  
    public String upload(HttpServletRequest request, HttpServletResponse response)  
    {  
        MultipartHttpServletRequest mulRequest = (MultipartHttpServletRequest) request;  
        MultipartFile file = mulRequest.getFile("excel");  
        String filename = file.getOriginalFilename();  
        if (filename == null || "".equals(filename))  
        {  
            return null;  
        }  
        try  
        {  
            InputStream input = file.getInputStream();  
            XSSFWorkbook workBook = new XSSFWorkbook(input);  
            XSSFSheet sheet = workBook.getSheetAt(0);  
            if (sheet != null)  
            {  
                for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++)  
                {  
                    XSSFRow row = sheet.getRow(i);  
                    for (int j = 0; j < row.getPhysicalNumberOfCells(); j++)  
                    {  
                        XSSFCell cell = row.getCell(j);  
                        String cellStr = cell.toString();  
                        System.out.print("【"+cellStr+"】 ");  
                    }  
                    System.out.println();  
                }  
  
            }  
        }  
        catch (Exception e)  
        {  
            e.printStackTrace();  
        }  
        return "/test/uploadExcel.jsp";  
    }  
  
}  


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SpringMVC导入Excel文件有多种方法,以下是其中一种常见的方法: 1. 准备Excel文件 首先需要准备一个Excel文件,可以使用Microsoft Excel或类似的软件创建。 2. 添加依赖 在pom.xml中添加Apache POI依赖,如下所示: ``` <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> ``` 3. 创建控制器 创建一个Spring MVC控制器来处理文件上传请求。在控制器中添加一个方法,该方法使用MultipartFile参数接收上传的文件,并使用Apache POI读取Excel文件中的数据。 ``` @Controller public class ExcelController { @PostMapping("/upload") public String uploadExcel(@RequestParam("file") MultipartFile file) throws IOException { Workbook workbook = new XSSFWorkbook(file.getInputStream()); Sheet sheet = workbook.getSheetAt(0); for (Row row : sheet) { for (Cell cell : row) { System.out.print(cell.getStringCellValue() + "\t"); } System.out.println(); } workbook.close(); return "redirect:/success"; } } ``` 4. 定义表单页面 在表单页面中添加一个文件上传组件,并将其提交到控制器中的uploadExcel方法。 ``` <form method="post" action="/upload" enctype="multipart/form-data"> <input type="file" name="file" /> <button type="submit">上传</button> </form> ``` 5. 运行应用程序 在浏览器中访问表单页面,选择要上传的Excel文件并提交表单。控制器将读取Excel文件中的数据并打印到控制台中。如果上传成功,将重定向到成功页面。 注意事项: - 在上传文件时,应该添加enctype="multipart/form-data"属性到表单标签中,否则文件将无法上传。 - Apache POI提供了许多API来处理Excel文件,可以根据具体需求进行选择。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值