java 读取excel获取真实行数

来源:互联网 发布:mac 安卓手机助手 编辑:程序博客网 时间:2024/05/19 03:46

java 读取excel获取真实行数

公司采用的是apache提供的包,通过XML文件的映射,把EXCEL表和我们的Model对应起来.本来是校验正确的,结果莫名其妙到后面就会报空指针异常. 
问题的原因:在没有格式的前提下,getLastRowNum方法能够正确返回最后一行的位置;getPhysicalNumberOfRows方法能够正确返回物理的行数; 
* 在有格式的前提下,这两个方法都是不合理的; 
* 所以,在做导入excel的时候,建议想要正确获取行数,可以做一个人为的约定,比如约定导入文件第一列不允许为空,行数就按照第一列的有效行数来统计;这样就能正确获取到实际想要的行数;

更新版本, 因为发现有时候 存在了加了样式的边框,边框的属性默认成为了 公式属性,导致后面空指针,现已修复

修改版:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. /** 
  2.     * 用来得到真实行数 
  3.     * @param sheet 
  4.     * @param flag  需要写进数据库的列数用逗号隔开 比如  (Sheet sheet,int 2,int 3);随意个 
  5.     * @return 
  6.     *  
  7.     */  
  8. ublic static int findRealRows(Sheet sheet, int... flag) {  
  9.        int row_real = 0;  
  10.        int rows = sheet.getPhysicalNumberOfRows();// 此处物理行数统计有错误,  
  11.        int size = flag.length;  
  12.        try {  
  13.   
  14.   
  15.        for (int i = 1; i < rows; i++) {  
  16.            Row row = sheet.getRow(i);  
  17.            int total = 0;  
  18.            ArrayList<Integer> blank =new ArrayList<Integer>();  
  19.            int type=-1;  
  20.            String s = null;  
  21.            for(int j:flag){  
  22.                if(!(row.getCell(j) == null)&&row.getCell(j).getCellType()<2){  
  23.                    type=row.getCell(j).getCellType();  
  24.                    row.getCell(j).setCellType(1);  
  25.                }  
  26.   
  27.                if (row.getCell(j) == null||row.getCell(j).getStringCellValue().matches("^\\s+$")||row.getCell(j).getCellType()>2) {  
  28.                    total++;  
  29.   
  30.                    if(!(row.getCell(j) == null)&&row.getCell(j).getCellType()<2){  
  31.                    row.getCell(j).setCellType(type);  
  32.                    }  
  33.                    blank.add(j);  
  34.   
  35.                }  
  36.            }  
  37.            System.out.println(s+"我");  
  38.            // 如果4列都是空说明就该返回  
  39.            if (total == flag.length) {  
  40.   
  41.                return row_real;  
  42.            } else if (total == 0) {  
  43.                row_real++;  
  44.   
  45.            } else {  
  46.                String h="";  
  47.                for(Integer b:blank){  
  48.   
  49.                     h=h+"第"+(b+1)+"列"+" ";  
  50.                }  
  51.                throw new BusinessException("第" + (i + 1) + "行" + h  
  52.                        + "不能为空");  
  53.            }  
  54.   
  55.        }  
  56.        } catch (NullPointerException e) {  
  57.            throw new BusinessException("excel格式异常,请检查excel格式有无数据缺失,无效数据行!");  
  58.        }  
  59.        return row_real;  
  60.    }  

方法都这样,通过约定一个有的ID来进行判断,可以较快的得到真实的行数 ,以至于后面的集合循环输出的话不会出现空指针异常


##利用POI在EXCEL表格中导入图片

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public void importExcelForCode(int x, int y, int width, int height,  
  2.             String no) throws Exception {  
  3.             //原装的EXCEL模板 如果要创建新的 在NWE XSSFWorkbook()中不需要带参数  
  4.         InputStream i = new FileInputStream("E:\\x.xlsx");  
  5.         //导入我的图片  
  6.         BufferedImage image = ImageIO.read(new File("E:\\name.jpg"));  
  7.         XSSFWorkbook xssfWorkbook = new XSSFWorkbook(i);  
  8.         XSSFSheet sheet = xssfWorkbook.getSheetAt(0);  
  9.         XSSFDrawing xssfDrawing = sheet.createDrawingPatriarch();  
  10.         //字节流  
  11.         ByteArrayOutputStream bao = new ByteArrayOutputStream();  
  12.         ImageIO.write(image, "jpg", bao);  
  13.                 //设置起始坐标,前四个是xy函数, 后四个是设置起始行列和图形行列 我选择后者  
  14.         XSSFClientAnchor anchor = new XSSFClientAnchor(0000, x, y, width  
  15.                 + x, height + y);  
  16.         anchor.setAnchorType(0);  
  17.         //创建图片  
  18.         xssfDrawing.createPicture(anchor, xssfWorkbook.addPicture(  
  19.                 bao.toByteArray(), XSSFWorkbook.PICTURE_TYPE_JPEG));  
  20.                 //关闭流  
  21.         i.close();  
  22.         FileOutputStream fos = new FileOutputStream(new File(  
  23.                 "E:\\x.xlsx"));  
  24.         xssfWorkbook.write(fos);  
  25.         new File("E:\\" + no + ".jpg").delete();  
  26.     }  

 ##使用Zxing打造带有数字的二维码
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. package com.x.ExportExcel;  
  2.   
  3. import java.awt.Color;  
  4. import java.awt.Font;  
  5. import java.awt.Graphics2D;  
  6. import java.awt.RenderingHints;  
  7. import java.awt.image.BufferedImage;  
  8. import java.io.ByteArrayOutputStream;  
  9. import java.io.File;  
  10. import java.io.FileInputStream;  
  11. import java.io.FileOutputStream;  
  12. import java.io.IOException;  
  13. import java.io.InputStream;  
  14. import java.util.Hashtable;  
  15.   
  16. import javax.imageio.ImageIO;  
  17.   
  18. import org.apache.poi.xssf.usermodel.XSSFClientAnchor;  
  19. import org.apache.poi.xssf.usermodel.XSSFDrawing;  
  20. import org.apache.poi.xssf.usermodel.XSSFSheet;  
  21. import org.apache.poi.xssf.usermodel.XSSFWorkbook;  
  22.   
  23. import com.google.zxing.BarcodeFormat;  
  24. import com.google.zxing.EncodeHintType;  
  25. import com.google.zxing.MultiFormatWriter;  
  26. import com.google.zxing.client.j2se.MatrixToImageWriter;  
  27. import com.google.zxing.common.BitMatrix;  
  28.   
  29. public class Code_128Utils {  
  30.   
  31.     private static final int WIDTH = 351;  
  32.     private static final int CODEHEIGHT = 55;  
  33.     private static final int HEIGHT = 78;  
  34.     private static final int FONTSIZE = 25;  
  35.     private static final String IMAGETYPE = "JPEG";  
  36.         //该方法用来生成所需二维码  不带数字  
  37.     public static void createCode(String no) throws Exception {  
  38.         FileOutputStream fos;  
  39.         fos = new FileOutputStream(new File("E:\\code\\" + no + ".jpg"));  
  40.         int width = WIDTH;  
  41.         int height = CODEHEIGHT;  
  42.         Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();  
  43.         hints.put(EncodeHintType.CHARACTER_SET, "utf-8");  
  44.         BitMatrix m = new MultiFormatWriter().encode(no,  
  45.                 BarcodeFormat.CODE_128, width, height, hints);  
  46.         MatrixToImageWriter.writeToStream(m, IMAGETYPE, fos);  
  47.         fos.flush();  
  48.         fos.close();  
  49.         createFont(no);  
  50.   
  51.     }  
  52.             ///该方法用来生成二维码字体并且把二维码拼接到字体图片上  
  53.     public static void createFont(String no) throws Exception {  
  54.         BufferedImage font = new BufferedImage(WIDTH, HEIGHT,  
  55.                 BufferedImage.TYPE_INT_RGB);  
  56.         BufferedImage code = ImageIO.read(new File("E:\\code\\" + no + ".jpg"));  
  57.         Graphics2D g = (Graphics2D) font.getGraphics();  
  58.         //长宽是总的 字体加二维码的  
  59.         g.clearRect(00, WIDTH, HEIGHT);  
  60.         g.setColor(Color.WHITE);  
  61.         g.fillRect(00, WIDTH, HEIGHT);  
  62.         //字体渲染  
  63.         g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,  
  64.                 RenderingHints.VALUE_ANTIALIAS_ON);  
  65.         g.setRenderingHint(RenderingHints.KEY_RENDERING,  
  66.                 RenderingHints.VALUE_RENDER_QUALITY);  
  67.                 //在图片上把字写好  
  68.         for (int i = 0; i < no.length(); i++) {  
  69.             g.setColor(Color.black);  
  70.             Font font_ = new Font("Consolas"0, FONTSIZE);  
  71.             g.setFont(font_);  
  72.             g.drawString(no.charAt(i) + "", (FONTSIZE * 2 + WIDTH - no.length()  
  73.                     * FONTSIZE)  
  74.                     / 2 + (i - 1) * FONTSIZE, CODEHEIGHT + HEIGHT - CODEHEIGHT);  
  75.         }  
  76.         //然后把二维码加上去   
  77.         g.drawImage(code, 00null);  
  78.         g.dispose();  
  79.         //进行图片处理,防止出现模糊  
  80.         int[] rgb = new int[3];  
  81.         for (int i = 0; i < WIDTH; i++) {  
  82.             for (int j = CODEHEIGHT; j < HEIGHT; j++) {  
  83.                 int pixel = font.getRGB(i, j);  
  84.                 rgb[0] = (pixel & 0xff0000) >> 16;  
  85.                 rgb[1] = (pixel & 0xff00) >> 8;  
  86.                 rgb[2] = (pixel & 0xff);  
  87.                 if (rgb[0] > 125 || rgb[1] > 125 || rgb[2] > 125) {  
  88.                     font.setRGB(i, j, -1);  
  89.                 }  
  90.                 if (rgb[0] < 100 || rgb[1] < 100 || rgb[2] < 100) {  
  91.                     font.setRGB(i, j, -16777216);  
  92.                 }  
  93.             }  
  94.         }  
  95.   
  96.         File outputfile = new File("E:\\code\\" + no + ".jpg");  
  97.         ImageIO.write(font, IMAGETYPE, outputfile);  
  98.     }  
  99.   
  100.   
  101. }  

生成二维码形状
0 0