zoukankan      html  css  js  c++  java
  • excel的导入导出

    最近刚注册的博客园,也想记录一些学到的知识拿出来和大家分享一下。最近做一个项目有涉及到excel表格的导入导出,详细的代码如下:

    public class ExcelUtils<T> {
    private static final SimpleDateFormat sdf = new SimpleDateFormat(
    "yyyy-MM-dd");

    /**
    * 导出excel文件
    *
    * @param title
    * 表格的名称
    * @param headers
    * 表格的标题名
    * @param list
    * 要导出的实体集合
    * @param out
    * 输出地点
    */
    public void exportExcel(String title, String[] headers, List<T> list,
    OutputStream out) {
        HSSFWorkbook wb = new HSSFWorkbook(); // 创建一个工作簿
        HSSFSheet sheet = wb.createSheet(title); // 创建一个表格
        sheet.setDefaultColumnWidth((short) 15); // 设置默认列宽
        HSSFCellStyle style1 = setTitleStyle(wb.createCellStyle(),
        wb.createFont());
        HSSFCellStyle style2 = setContentStyle(wb.createCellStyle(),
        wb.createFont());
    // 创建第一行,即标题栏
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
        HSSFCell cell = row.createCell(i, HSSFCell.CELL_TYPE_STRING);
        cell.setCellStyle(style1);
        cell.setCellValue(headers[i]);
     }
        for (int i = 0; i < list.size(); i++) {
        T t = (T) list.get(i);
        row = sheet.createRow(i + 1);
        Field[] fields = t.getClass().getDeclaredFields();
        for (int j = 0; j < fields.length; j++) {
        HSSFCell cell = row.createCell(j);
        cell.setCellStyle(style2);
        String fieldName = fields[j].getName();
        String getMethodName = "get"
        + fieldName.substring(0, 1).toUpperCase()
        + fieldName.substring(1);
         try {
        Class tCls = t.getClass();
        Method getMethod = tCls.getMethod(getMethodName,
        new Class[] {});
        Object value = getMethod.invoke(t, new Object[] {});
        String textValue = null;
        if (value instanceof Date) {
        Date date = (Date) value;
        SimpleDateFormat sdf = new SimpleDateFormat(
       "yyyy-MM-dd");
       textValue = sdf.format(date);
       cell.setCellValue(textValue);
       } else {
      // 其它数据类型都当作字符串简单处理
       textValue = value.toString();
       cell.setCellValue(textValue);
     }
     } catch (Exception e) {
    e.printStackTrace();
        }
       }
    }
        try {
    // 写进输出流中
       wb.write(out);
       } catch (IOException e) {
          e.printStackTrace();
       } finally {
        try {
        if (wb != null)
        wb.close();
    }   catch (IOException e) {
         e.printStackTrace();
        }
       }
    }

    /**
    *
    * 描述:读取excel数据
    * @param in 打开了excel文件的输入流,会自动调用close()方法。
    * @return 返回字符串数组集合。一个数组下标对应一个单元格的数据,一个list对应一行数据。
    */
        public List<String[]> importExcel(InputStream in) {
        HSSFWorkbook wb = null;
        List<String[]> list = new ArrayList<String[]>();
        try {
           wb = new HSSFWorkbook(in);
        for (int i = 0; i < wb.getNumberOfSheets(); i++) {
        HSSFSheet sheet = wb.getSheetAt(i);
        for (int j = 1; j < sheet.getPhysicalNumberOfRows(); j++) {
        HSSFRow row = sheet.getRow(j);
        int cellNum = row.getLastCellNum();
        String[] obj = new String[cellNum];
        for (int k = 0; k < cellNum; k++) {
        obj[k] = judgeType(row.getCell(k));
     }
       list.add(obj);
      }
     }
    } catch (IOException e) {
         e.printStackTrace();
      } finally {
      try {
         wb.close();
         in.close();
     } catch (IOException e) {
         e.printStackTrace();
     }
    }
       return list;
    }

    /**
    *
    * 描述:判断单元格数据类型
    *
    * @param cell
    * 单元格
    * @return 表格数据
    */
        String judgeType(HSSFCell cell) {
        String value = null;
        switch (cell.getCellType()) {
        case HSSFCell.CELL_TYPE_STRING:
        value = cell.getStringCellValue();
        break;
        case HSSFCell.CELL_TYPE_BLANK:
        value = cell.getStringCellValue();
        break;
        case HSSFCell.CELL_TYPE_NUMERIC:
        if (DateUtil.isCellDateFormatted(cell)) {
        value = sdf.format(cell.getDateCellValue());
      } else {
        value = "" + cell.getNumericCellValue();
     }
       break;
       default:
       value = "";
       break;
      }
       return value;
    }

    /**
    *
    * 描述:设置标题样式
    *
    * @param style
    * @param font
    * @return
    */
    HSSFCellStyle setTitleStyle(HSSFCellStyle style, HSSFFont font) {
    // 设置样式
    style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
    style.setBorderRight(HSSFCellStyle.BORDER_THIN);
    style.setBorderTop(HSSFCellStyle.BORDER_THIN);
    style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    font.setFontHeightInPoints((short) 12);
    font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    // 把字体应用到当前的样式
    style.setFont(font);
    return style;
    }

    /**
    *
    * 描述:设置内容样式
    *
    * @param style
    * @param font
    * @return
    */
    HSSFCellStyle setContentStyle(HSSFCellStyle style, HSSFFont font) {
    // 设置样式
    style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
    style.setBorderRight(HSSFCellStyle.BORDER_THIN);
    style.setBorderTop(HSSFCellStyle.BORDER_THIN);
    style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    font.setFontHeightInPoints((short) 12);
    style.setFont(font);
    return style;
    }

    如有不足请大家指出缺点。

  • 相关阅读:
    myeclipse/eclipse安装反编译插件jadclipse
    【java报错】Unknown character set index for field '224' received from server.
    myeclipse安装插件phpeclipse后进行PHP代码编写
    MyEclipse/Eclipse安装插件的几种方式
    利用eclipse调试ofbiz之debug使用
    SAE如何使用Git
    Git入门及上传项目到github中
    Smarty模板快速入门
    访问WEB-INF目录中的文件
    httprunner系列06——参数化&csv文件
  • 原文地址:https://www.cnblogs.com/xiuxun/p/5855792.html
Copyright © 2011-2022 走看看