java poi excel 导入导出数据

背景:1.pringmvc 框架下 的excel 导入导出

     2.OI 操作office.

 

页面代码:

    <div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">

      <div class="modal-dialog modal-lg" style="width:400px;">

        <div class="modal-content">

            <div style="height:300px;padding:10px;">

                <h1>批量导入商品信息</h1>

                <div style="margin-top:20px;padding:0px 5px 15px 5px;">

                    <span><strong>1.下载模板 > 2.导入模板 >3.导入完成</strong></span><br/>

                    <span><strong>温馨提示:</strong></span>

                    <div style="line-height:50px;">导入模板格式不能修改,否则会导致导入失败!</div>

                    <a  href="${webRoot}/product/downExcel">下载导入模板</a>

                </div>

                <div>

                    <form action="${webRoot}/product/importExcel" id="excelForm" method="post" enctype="multipart/form-data">

                    <input type="file" name="file" />

                        <div style="text-align:right;padding-right:50px;">

                            <button type="button" id="import" class="btn btn-default" >导入</button>

                            <script>

                                $("#import").click(function(){

                                    $("#excelForm").submit();

                                });

                            </script>

                        </div>

                    </form>

                </div>

            </div>

        </div>

      </div>

    </div>

Controller 代码:

@RequestMapping("importExcel")

    public String addComm(ModelMap model, HttpServletRequest request) {

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

        MultipartFile file = multipartRequest.getFile("file");

        String[][] result = null;

        ExportUtil exportUtil = new ExportUtil();  

        try {

            exportUtil.SaveFileFromInputStream(file.getInputStream(),

                    request.getSession().getServletContext()

                    .getRealPath(File.separator)+"upload", "product.xls");

        File file1 = new File(request.getSession().getServletContext()

                .getRealPath(File.separator)+"upload" + "/product.xls");

            result =exportUtil.getData(file1, 4);

        } catch (Exception ex) {

            System.out.println("上传文件失败");

            ex.printStackTrace();

        }

        if (result == null) 

            return null;

        User user = (User)request.getSession().getAttribute("user");

        if(user==null) return "";

        int rowLength = result.length;

        List<Product> proList =exportUtil.doProduct(rowLength, result,user);

        ps.excelAdd(proList);

        return "redirect:/product/getproduct";

    }

    @RequestMapping("downExcel")

    @ResponseBody

    public String downExcel(HttpServletResponse response){

        try {

            ServletOutputStream outputStream = response.getOutputStream();

        

        String fileName = new String(("商品导入模板").getBytes(), "ISO8859_1");  

        response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");// 组装附件名称和格式

        es.exportExcel(outputStream,false);

        } catch (IOException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }  

        return "";

    }

    

    

    @RequestMapping("exportExcel")

    @ResponseBody

    public String exportExcel(HttpServletResponse response){

        try {

            ServletOutputStream outputStream = response.getOutputStream();

        

        String fileName = new String(("蓝图进销存商品导出").getBytes(), "ISO8859_1");  

        response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");// 组装附件名称和格式

        es.exportExcel(outputStream,true);

        } catch (IOException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }  

        return "";

    }

ExportService:

package com.ly.jxc.service;



import java.io.IOException;

import java.util.List;



import javax.annotation.Resource;

import javax.servlet.ServletOutputStream;



import org.apache.poi.hssf.usermodel.HSSFCell;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;

import org.apache.poi.hssf.usermodel.HSSFRow;

import org.apache.poi.hssf.usermodel.HSSFSheet;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.ss.util.CellRangeAddress;

import org.springframework.stereotype.Service;

import com.ly.jxc.dao.ProductClassDAO;

import com.ly.jxc.dao.ProductDAO;

import com.ly.jxc.dao.ProductUnitDAO;

import com.ly.jxc.entity.Product;

import com.ly.jxc.entity.ProductClass;

import com.ly.jxc.entity.ProductUnit;

import com.ly.jxc.util.ExportUtil;



@Service

public class ExportService {

    @Resource

    private ProductUnitDAO pud;

    @Resource

    private ProductClassDAO pcd;

    @Resource

    private ProductDAO pd;

      public void exportExcel(ServletOutputStream outputStream,boolean isDwon)  

        {  

            List<ProductUnit> puList = pud.getAllUnit();

            List<ProductClass> pcList = pcd.GetAllProductClass();

            // 创建一个workbook 对应一个excel应用文件   

            // HSSWorkbook 是03版excel 的个格式,XSSWorkbook 是07以上版本,HSS 和 XSS 开头分别代表03,07可以切换

            HSSFWorkbook workBook = new HSSFWorkbook();  

            // 在workbook中添加一个sheet,对应Excel文件中的sheet  

            HSSFSheet sheet = workBook.createSheet("商品导入导出"); 

            //表格默认行宽度

            sheet.setDefaultColumnWidth(15);

            sheet.setDefaultRowHeightInPoints(100);

            

            ExportUtil exportUtil = new ExportUtil(workBook, sheet);  

            //设置单元格格式

            HSSFCellStyle headStyle = exportUtil.getHeadStyle(false);  

            HSSFCellStyle bodyStyle = exportUtil.getBodyStyle();  

            //创建单元格

            HSSFCell cell = null;  

            //合并单元格

            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 8));

            //创建一行

            HSSFRow descRow = sheet.createRow(0);  

            //设置行高 单位是像素

            descRow.setHeightInPoints(80);

            //表示穿件的单元格是在第一行

            cell=descRow.createCell(0);

            //设置单元格格式

            cell.setCellStyle(exportUtil.getHeadStyle(true));  

            //设置单元格值

            cell.setCellValue("商品单位和类型填写必须填写对应的数字ID,否则会导入失败!"); 

            

            // 构建表头  

            HSSFRow unitRow = sheet.createRow(1);  

            unitRow.setHeightInPoints(40);

            cell=unitRow.createCell(0);

            cell.setCellStyle(headStyle);  

            cell.setCellValue("商品单位-ID:");  



            // 构建商品单位数据,动态构建导出数据

            if (puList != null && puList.size() > 0)  

            {  

                for (int j = 0; j < puList.size(); j++)  

                {  

                    ProductUnit pu = puList.get(j);

                    cell=unitRow.createCell(j+1);

                    cell.setCellStyle(bodyStyle);  

                    cell.setCellValue(pu.getName()+"--"+pu.getpId());  

                } 

            }

            // 构建商品类型表头 ,动态构建导出数据 

            HSSFRow classRow = sheet.createRow(2);  

            classRow.setHeightInPoints(40);

            cell=classRow.createCell(0);

            cell.setCellStyle(headStyle);  

            cell.setCellValue("商品类型-ID:");

            // 构建商品类型数据  

            if (pcList != null && pcList.size() > 0)  

            {  

                for (int j = 0; j < pcList.size(); j++)  

                {  

                    ProductClass pc = pcList.get(j);

                    cell=classRow.createCell(j+1);

                    cell.setCellStyle(bodyStyle);  

                    cell.setCellValue(pc.getName()+"--"+pc.getProductClass_ID());  

                } 

            }

               

              

                HSSFRow bodyRow = sheet.createRow(3);  

                bodyRow.setHeightInPoints(40);

  

                cell = bodyRow.createCell(0);  

                cell.setCellStyle(headStyle);  

                cell.setCellValue("条码");  

  

                cell = bodyRow.createCell(1);  

                cell.setCellStyle(headStyle);  

                cell.setCellValue("名字");  

  

                cell = bodyRow.createCell(2);  

                cell.setCellStyle(headStyle);  

                cell.setCellValue("类别ID");  

                

                cell = bodyRow.createCell(3);  

                cell.setCellStyle(headStyle);  

                cell.setCellValue("产品规格"); 

                

                cell = bodyRow.createCell(4);  

                cell.setCellStyle(headStyle);  

                cell.setCellValue("产品单位"); 

                

                cell = bodyRow.createCell(5);  

                cell.setCellStyle(headStyle);  

                cell.setCellValue("出售价格");  

                

                cell = bodyRow.createCell(6);  

                cell.setCellStyle(headStyle);  

                cell.setCellValue("进货价格"); 

                

                cell = bodyRow.createCell(7);  

                cell.setCellStyle(headStyle);  

                cell.setCellValue("最低价格");  

                

                cell = bodyRow.createCell(8);  

                cell.setCellStyle(headStyle);  

                cell.setCellValue("备注");  

                //如果是导出商品,则需要将商品数据写入

                if(isDwon){

                    

                    List<Product> proList = pd.getAllProducts();

                    for (int i = 0; i < proList.size(); i++) {

                            Product p =proList.get(i);

                           HSSFRow dateRow = sheet.createRow(4+i);  

                           bodyRow.setHeightInPoints(40);

                           

                           cell = dateRow.createCell(0);  

                           cell.setCellStyle(bodyStyle);  

                           cell.setCellValue(p.getpId());  

                           

                           cell = dateRow.createCell(1);  

                           cell.setCellStyle(bodyStyle);  

                           cell.setCellValue(p.getName());  

                           

                           cell = dateRow.createCell(2);  

                           cell.setCellStyle(bodyStyle);  

                           cell.setCellValue(p.getpList());  

                           

                           cell = dateRow.createCell(3);  

                           cell.setCellStyle(bodyStyle);  

                           cell.setCellValue(p.getPsID());  

                           

                           cell = dateRow.createCell(4);  

                           cell.setCellStyle(bodyStyle);  

                           cell.setCellValue(p.getpUtilId()); 

                           

                           cell = dateRow.createCell(5);  

                           cell.setCellStyle(bodyStyle);  

                           cell.setCellValue(p.getPrice());  

                           

                           cell = dateRow.createCell(6);  

                           cell.setCellStyle(bodyStyle);  

                           cell.setCellValue(p.getStockPrice());  

                           

                           cell = dateRow.createCell(7);  

                           cell.setCellStyle(bodyStyle);  

                           cell.setCellValue(p.getLowestPrice());  

                           

                           cell = dateRow.createCell(8);  

                           cell.setCellStyle(bodyStyle);  

                           cell.setCellValue(p.getRemark());         

                    }    

                }

            try  

            {  

                workBook.write(outputStream);  

                outputStream.flush();  

                outputStream.close();  

            }  

            catch (IOException e)  

            {  

                e.printStackTrace();  

            }  

            finally  

            {  

                try  

                {  

                    outputStream.close();  

                }  

                catch (IOException e)  

                {  

                    e.printStackTrace();  

                }  

            }  

      

        }  

    

}

辅助类ExportUtil:

package com.ly.jxc.util;



import java.io.BufferedInputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.text.DecimalFormat;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.Date;

import java.util.List;



import javax.servlet.http.HttpSession;



import org.apache.poi.hssf.usermodel.HSSFCell;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;

import org.apache.poi.hssf.usermodel.HSSFFont;

import org.apache.poi.hssf.usermodel.HSSFRow;

import org.apache.poi.hssf.usermodel.HSSFSheet;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.hssf.util.HSSFColor;

import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import org.apache.poi.ss.util.CellRangeAddress;



import org.apache.poi.xssf.usermodel.XSSFCellStyle;

import org.apache.poi.xssf.usermodel.XSSFFont;

import org.springframework.beans.factory.annotation.Autowired;



import com.ly.jxc.entity.Product;

import com.ly.jxc.entity.User;



public class ExportUtil {



    private HSSFWorkbook wb = null;



    private HSSFSheet sheet = null;

    @Autowired

HttpSession session;

    /**

     * @param wb

     * @param sheet

     */

    public ExportUtil(HSSFWorkbook wb, HSSFSheet sheet) {

        this.wb = wb;

        this.sheet = sheet;

    }



    public ExportUtil() {

    }



    /**

     * 合并单元格后给合并后的单元格加边框

     * 

     * @param region

     * @param cs

     */

    public void setRegionStyle(CellRangeAddress region, XSSFCellStyle cs) {

        int toprowNum = region.getFirstRow();

        for (int i = toprowNum; i <= region.getLastRow(); i++) {

            HSSFRow row = sheet.getRow(i);

            for (int j = region.getFirstColumn(); j <= region.getLastColumn(); j++) {

                HSSFCell cell = row.getCell(j);// XSSFCellUtil.getCell(row,

                                                // (short) j);

                cell.setCellStyle(cs);

            }

        }

    }



    /**

     * 设置表头的单元格样式

     * 

     * @return

     */

    public HSSFCellStyle getHeadStyle(boolean isalert) {

        // 创建单元格样式

        HSSFCellStyle cellStyle = wb.createCellStyle();

        // 设置单元格的背景颜色为淡蓝色

        if (!isalert)

            cellStyle.setFillForegroundColor(HSSFColor.PALE_BLUE.index);

        else

            cellStyle.setFillForegroundColor(HSSFColor.RED.index);

        cellStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);

        // 设置单元格居中对齐

        cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);

        // 设置单元格垂直居中对齐

        cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);

        // 创建单元格内容显示不下时自动换行

        cellStyle.setWrapText(true);

        // 设置单元格字体样式

        HSSFFont font = wb.createFont();

        // 设置字体加粗

        font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);

        font.setFontName("宋体");

        if (isalert) {

            font.setColor(HSSFColor.WHITE.index);

        }

        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 HSSFCellStyle getBodyStyle() {

        // 创建单元格样式

        HSSFCellStyle cellStyle = wb.createCellStyle();



        // 设置单元格居中对齐

        cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);

        // 设置单元格垂直居中对齐

        cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);

        // 创建单元格内容显示不下时自动换行

        cellStyle.setWrapText(true);

        // 设置单元格字体样式

        HSSFFont 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;

    }



    // 将MultipartFile 转换为File

    public static void SaveFileFromInputStream(InputStream stream, String path,

            String savefile) throws IOException {

        FileOutputStream fs = new FileOutputStream(path + "/" + savefile);

        // System.out.println("------------"+path + "/"+ savefile);

        byte[] buffer = new byte[1024 * 1024];

        int bytesum = 0;

        int byteread = 0;

        while ((byteread = stream.read(buffer)) != -1) {

            bytesum += byteread;

            fs.write(buffer, 0, byteread);

            fs.flush();

        }

        fs.close();

        stream.close();

    }



    /**

     * 

     * 读取Excel的内容,第一维数组存储的是一行中格列的值,二维数组存储的是多少个行

     * 

     * @param file

     *            读取数据的源Excel

     * 

     * @param ignoreRows

     *            读取数据忽略的行数,比喻行头不需要读入 忽略的行数为1

     * 

     * @return 读出的Excel中数据的内容

     * 

     * @throws FileNotFoundException

     * 

     * @throws IOException

     */



    public static String[][] getData(File file, int ignoreRows)throws Exception {

        List<String[]> result = new ArrayList<String[]>();

        int rowSize = 0;

        BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));

        // 打开HSSFWorkbook

        POIFSFileSystem fs = new POIFSFileSystem(in);

        HSSFWorkbook wb = new HSSFWorkbook(fs);

        HSSFCell cell = null;

        for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) {

            HSSFSheet st = wb.getSheetAt(sheetIndex);

            // 第一行为标题,不取

            for (int rowIndex = ignoreRows; rowIndex <= st.getLastRowNum(); rowIndex++) {

                HSSFRow row = st.getRow(rowIndex);

                if (row == null) {

                    continue;

                }

                int tempRowSize = row.getLastCellNum() + 1;

                if (tempRowSize > rowSize) {

                    rowSize = tempRowSize;

                }

                String[] values = new String[rowSize];

                Arrays.fill(values, "");

                boolean hasValue = false;

                for (short columnIndex = 0; columnIndex <= row.getLastCellNum(); columnIndex++) {

                    String value = "";

                    cell = row.getCell(columnIndex);

                    if (cell != null) {

                        // 注意:一定要设成这个,否则可能会出现乱码

                        switch (cell.getCellType()) {

                        case HSSFCell.CELL_TYPE_STRING:

                            value = cell.getStringCellValue();

                            break;

                        case HSSFCell.CELL_TYPE_NUMERIC:

                            if (HSSFDateUtil.isCellDateFormatted(cell)) {

                                Date date = cell.getDateCellValue();

                                if (date != null) {

                                    value = new SimpleDateFormat("yyyy-MM-dd").format(date);

                                } else {

                                    value = "";

                                }

                            } else {

                                value = new DecimalFormat("0").format(cell.getNumericCellValue());

                            }

                            break;

                        case HSSFCell.CELL_TYPE_FORMULA:

                            // 导入时如果为公式生成的数据则无值

                            if (!cell.getStringCellValue().equals("")) {

                                value = cell.getStringCellValue();

                            } else {

                                value = cell.getNumericCellValue() + "";

                            }

                            break;

                        case HSSFCell.CELL_TYPE_BLANK:

                            break;

                        case HSSFCell.CELL_TYPE_ERROR:

                            value = "";

                            break;

                        case HSSFCell.CELL_TYPE_BOOLEAN:

                            value = (cell.getBooleanCellValue() == true ? "Y"

                            : "N");

                            break;

                        default:

                            value = "";

                        }

                    }

                    if (columnIndex == 0 && value.trim().equals("")) {

                        break;

                    }

                    values[columnIndex] = rightTrim(value);

                    hasValue = true;

                }

                if (hasValue) {

                    result.add(values);

                }

            }

        }

        in.close();

        String[][] returnArray = new String[result.size()][rowSize];

        for (int i = 0; i < returnArray.length; i++) {

            returnArray[i] = (String[]) result.get(i);

        }

        return returnArray;

    }



    /**

     * 

     * 去掉字符串右边的空格

     * 

     * @param str

     *            要处理的字符串

     * 

     * @return 处理后的字符串

     */



    public static String rightTrim(String str) {

        if (str == null) {

            return "";

        }

        int length = str.length();

        for (int i = length - 1; i >= 0; i--) {

            if (str.charAt(i) != 0x20) {

                break;

            }

            length--;

        }

        return str.substring(0, length);

    }

    public List<Product> doProduct(int rowLength,String[][] result,User user){

        // 默认从1 开始 本来是为0 剔除掉



                List<Product> proList = new ArrayList<Product>();

                Date date = new Date();

                for (int i = 0; i < rowLength; i++) {

                    Product pro = new Product();



                    for (int j = 0; j < result[i].length; j++) {// 默认从1开始添加

                        // 客户ID 客户名 客户类型 客户电话 客户状态 创建时间 放出时间 跟入时间 跟入人 放出人

                        // 27 法规和热 特级 1212121 1 41773 2014-05-14 10:20:48.0 yq1012

                        // 整理 id 去掉 。 创建时间 换成当前时间,,,放出时间 跟入时间 跟入人 放出人----全不要

                        // 格式如上

                        // System.out.print(result[i][j]+"\t\t");

                        if (j == 0) // 编码

                            pro.setpId(result[i][j]);

                        if (j == 1) // 名字

                            pro.setName(result[i][j]);

                        if (j == 2) // 类别

                            pro.setpList(Integer.parseInt(result[i][j]));

                        if (j == 3) // 商品规格

                            pro.setPsID(result[i][j]);

                        if (j == 4)// 单位

                            pro.setpUtilId(Integer.parseInt(result[i][j]));

                        if (j == 5)// 出售价格

                            pro.setPrice(Double.parseDouble(result[i][j]));

                        if (j == 6) // 进货价格

                            pro.setStockPrice(Double.parseDouble(result[i][j]));

                        if (j == 7)// 最低价格

                            pro.setLowestPrice(Double.parseDouble(result[i][j]));

                        if (j == 8)// 备注

                            pro.setRemark(result[i][j]);

                        

                    }

                    

                    pro.setUserId(user.getUser_Id());

                    proList.add(pro);

                    // crmService.saveCrmUser(crm);

                }

                return proList;

    }



}

 

你可能感兴趣的:(Java POI)