• java操作 读写取 excel poi.jar


    package com.ywx.test.poi;
    
    import java.io.BufferedInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    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 org.apache.poi.hssf.usermodel.HSSFCell;
    import org.apache.poi.hssf.usermodel.HSSFDateUtil;
    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.poifs.filesystem.POIFSFileSystem;
    
     
    
    public class PoiReadExcel {
    
     
    
        public static void main(String[] args) throws Exception {
    
           File file = new File("d:\ExcelDemo.xls");
    
           String[][] result = getData(file, 1);
    
           int rowLength = result.length;
    
           for(int i=0;i<rowLength;i++) {
    
               for(int j=0;j<result[i].length;j++) {
    
                  System.out.print(result[i][j]+"		");
    
               }
    
               System.out.println();
    
           }
    
          
    
        }
    
        /**
    
         * 读取Excel的内容,第一维数组存储的是一行中格列的值,二维数组存储的是多少个行
    
         * @param file 读取数据的源Excel
    
         * @param ignoreRows 读取数据忽略的行数,比喻行头不需要读入 忽略的行数为1
    
         * @return 读出的Excel中数据的内容
    
         * @throws FileNotFoundException
    
         * @throws IOException
    
         */
    
        public static String[][] getData(File file, int ignoreRows)
    
               throws FileNotFoundException, IOException {
    
           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) {
    
                         // 注意:一定要设成这个,否则可能会出现乱码
    
                         //cell.setEncoding(HSSFCell.ENCODING_UTF_16);
    
                         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);
    
        }
    
    }
    View Code

    package com.ywx.test.poi;
    
    import java.io.IOException;
    import java.io.OutputStream;
    import java.lang.reflect.Field;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.text.SimpleDateFormat;
    import java.util.Collection;
    import java.util.Date;
    import java.util.Iterator;
    
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    
    import org.apache.poi.hssf.usermodel.HSSFCell;
    import org.apache.poi.hssf.usermodel.HSSFCellStyle;
    import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
    import org.apache.poi.hssf.usermodel.HSSFComment;
    import org.apache.poi.hssf.usermodel.HSSFFont;
    import org.apache.poi.hssf.usermodel.HSSFPatriarch;
    import org.apache.poi.hssf.usermodel.HSSFRichTextString;
    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;
    
      
    public class PoiWriteExcel<T>{
        
        public void exportExcel(Collection<T> dataset, OutputStream out) {
            exportExcel("导出EXCEL文档", null, dataset, out, "yyyy-MM-dd");
        }
    
        public void exportExcel(String[] headers, Collection<T> dataset,
                OutputStream out) {
            exportExcel("导出EXCEL文档", headers, dataset, out, "yyyy-MM-dd");
        }
    
        public void exportExcel(String[] headers, Collection<T> dataset,
                OutputStream out, String pattern) {
            exportExcel("导出EXCEL文档", headers, dataset, out, pattern);
        }
    
        /**
         * 这是一个通用的方法,利用了JAVA的反射机制,可以将放置在JAVA集合中并且符号一定条件的数据以EXCEL 的形式输出到指定IO设备上
         * 
         * @param title
         *            表格标题名
         * @param headers
         *            表格属性列名数组
         * @param dataset
         *            需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的
         *            javabean属性的数据类型有基本数据类型及String,Date,byte[](图片数据)
         * @param out
         *            与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
         * @param pattern
         *            如果有时间数据,设定输出格式。默认为"yyy-MM-dd"
         */
        @SuppressWarnings("unchecked")
        public void exportExcel(String title, String[] headers,
                Collection<T> dataset, OutputStream out, String pattern) {
            // 声明一个工作薄
            HSSFWorkbook workbook = new HSSFWorkbook();
            // 生成一个表格
            HSSFSheet sheet = workbook.createSheet(title);
            // 设置表格默认列宽度为15个字节
            sheet.setDefaultColumnWidth((short) 18);
            // 生成一个样式
            HSSFCellStyle style = workbook.createCellStyle();
            // 设置这些样式
            style.setFillForegroundColor(HSSFColor.WHITE.index);
            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);
            // 生成一个字体
            HSSFFont font = workbook.createFont();
            font.setColor(HSSFColor.VIOLET.index);
            font.setFontHeightInPoints((short) 15);
            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            // 把字体应用到当前的样式
            style.setFont(font);
            // 生成并设置另一个样式
            HSSFCellStyle style2 = workbook.createCellStyle();
            style2.setFillForegroundColor(HSSFColor.WHITE.index);
            style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
            style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
            style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
            // 生成另一个字体
            HSSFFont font2 = workbook.createFont();
            font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
            // 把字体应用到当前的样式
            style2.setFont(font2);
            
            // 声明一个画图的顶级管理器
            HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
            // 定义注释的大小和位置,详见文档
            HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5));
            // 设置注释内容
            comment.setString(new HSSFRichTextString("可以在POI中添加注释!"));
            // 设置注释作者,当鼠标移动到单元格上是可以在状态栏中看到该内容.
            comment.setAuthor("leno");
    
            //产生表格标题行
            HSSFRow row = sheet.createRow(0);
            if(headers!=null&&headers.length!=0){
                for (short i = 0; i < headers.length; i++) {
                    HSSFCell cell = row.createCell(i);
                    cell.setCellStyle(style);
                    HSSFRichTextString text = new HSSFRichTextString(headers[i]);
                    cell.setCellValue(text);
                }
            }
    
            //遍历集合数据,产生数据行
            Iterator<T> it = dataset.iterator();
            int index = 0;
            while (it.hasNext()) {
                index++;
                row = sheet.createRow(index);
                T t = (T) it.next();
                //利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
                Field[] fields = t.getClass().getDeclaredFields();
                for (short i = 0; i < fields.length; i++) {
                    HSSFCell cell = row.createCell(i);
                    cell.setCellStyle(style2);
                    Field field = fields[i];
                    String fieldName = field.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 Boolean) {
                            boolean bValue = (Boolean) value;
                            textValue = "";
                            if (!bValue) {
                                textValue ="";
                            }
                        } else if (value instanceof Date) {
                            Date date = (Date) value;
                            SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                             textValue = sdf.format(date);
                        }  else if (value instanceof byte[]) {
                            // 有图片时,设置行高为60px;
                            row.setHeightInPoints(60);
                            // 设置图片所在列宽度为80px,注意这里单位的一个换算
                            sheet.setColumnWidth(i, (short) (35.7 * 80));
                            // sheet.autoSizeColumn(i);
                            byte[] bsValue = (byte[]) value;
                            HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0,
                                    1023, 255, (short) 6, index, (short) 6, index);
                            anchor.setAnchorType(2);
                            patriarch.createPicture(anchor, workbook.addPicture(
                                    bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG));
                        } else if (value instanceof Integer || value instanceof String ||value instanceof Double) {
                            //其它数据类型都当作字符串简单处理
                            textValue = value.toString();
                        }
                        //如果不是图片数据,就利用正则表达式判断textValue是否全部由数字组成
                        if(textValue!=null){
                            Pattern p = Pattern.compile("^\d+(\.\d+)?$");   
                            Matcher matcher = p.matcher(textValue);
                            if(matcher.matches()){
                                //是数字当作double处理
                                cell.setCellValue(Double.parseDouble(textValue));
                            }else{
                                HSSFRichTextString richString = new HSSFRichTextString(textValue);
                                HSSFFont font3 = workbook.createFont();
                                font3.setColor(HSSFColor.BLUE.index);
                                richString.applyFont(font3);
                                cell.setCellValue(richString);
                            }
                        }
                    } catch (SecurityException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (NoSuchMethodException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IllegalArgumentException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } finally {
                        //清理资源
                    }
                }
    
            }
            try {
                workbook.write(out);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
        }
    
        public static void main(String[] args) {
        
        }
    }
    View Code
    package com.ywx.test.poi;
    
    public class TestWrite {
        public static void main(String[] args) {}
    }
    
    
    
    
    /*
    ExportExcel1<UsersVO> excell = new ExportExcel1<UsersVO>();
    String[] headers = { "客户编号",
                        "客户名字", 
                        "客户性别(1->男,0->女)", 
                        "客户年龄", 
                        "客户生日", 
                        "身份证号", 
                        "家庭住址",
                        "电子邮件", 
                        "联系方式",
                        "身体状况",
                        "用户密码"};
    
    ArrayList<UsersVO> list1 =useSer.getAllUsersInfo();
    
    response.setContentType("octets/stream");
    try {
        response.addHeader(
                "Content-Disposition",
                "attachment;filename="
                        + new String("客户.xls".getBytes("utf-8"),
                                "iso8859-1"));
    //    response.addHeader(
    //            "Content-Disposition",
    //            "attachment;filename="+"1.xls");
        OutputStream out2 = response.getOutputStream();
        excell.exportExcel(headers, list1, out2);
        out2.flush();
        out2.close();
        int count=1;
    } catch (FileNotFoundException e) {
        try {
            
            response.getWriter().print("lost");
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    
    } catch (Exception e) {
        try {
            e.printStackTrace();
            response.getWriter().print("fail");
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e1) {
            
            e1.printStackTrace();
        }
    }*/
    View Code
  • 相关阅读:
    PHP获取当前页面完整URL的方法
    PHP中常见的提示对照表
    PHP语言中使用JSON和将json还原成数组
    PHP中被定义为false的
    yum
    PHP中计划任务
    command shell 的知识整理
    js的包管理工具bower安装
    Shell脚本
    liunx中计算机壳层
  • 原文地址:https://www.cnblogs.com/super-admin/p/5601930.html
Copyright © 2020-2023  润新知