java poi 读取Excel中的手机号
使用poi读取Excel手机号,通常会把它认为成double类型,然后使用科学计数法显示1.32....E10什么的,很苦恼。刚刚查了官方文档https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/DataFormatter.html,简单的很,代码如下:
使用DataFormatter格式化一下即可。
1 package cn.gx.test; 2 3 import java.io.File; 4 import java.io.FileInputStream; 5 import java.io.FileNotFoundException; 6 import java.io.IOException; 7 import java.io.InputStream; 8 import java.util.logging.Level; 9 import java.util.logging.Logger; 10 11 import org.apache.poi.ss.usermodel.DataFormatter; 12 import org.apache.poi.xssf.usermodel.XSSFRow; 13 import org.apache.poi.xssf.usermodel.XSSFSheet; 14 import org.apache.poi.xssf.usermodel.XSSFWorkbook; 15 16 public class ExcelRead { 17 18 public ExcelRead() { 19 20 } 21 22 public void testPoiExcel2007(InputStream ios) { 23 // 构造 XSSFWorkbook 对象,strPath 传入文件路径 24 XSSFWorkbook xwb = null; 25 try { 26 xwb = new XSSFWorkbook(ios); 27 } catch (IOException e) { 28 // TODO Auto-generated catch block 29 e.printStackTrace(); 30 } 31 // 读取第一章表格内容 32 XSSFSheet sheet = xwb.getSheetAt(0); 33 // 定义 row、cell 34 XSSFRow row; 35 String cell; 36 // 循环输出表格中的内容 37 for (int i = sheet.getFirstRowNum(); i < sheet 38 .getPhysicalNumberOfRows(); i++) { 39 row = sheet.getRow(i); 40 for (int j = row.getFirstCellNum(); j < row 41 .getPhysicalNumberOfCells(); j++) { 42 // 通过 row.getCell(j).toString() 获取单元格内容, 43 int cellType = row.getCell(j).getCellType(); 44 // System.out.println("cellType:"+cellType); 45 if (cellType == 0) { 46 DataFormatter dataFormatter = new DataFormatter(); 47 dataFormatter.addFormat("###########", null); 48 cell = dataFormatter.formatCellValue(row.getCell(j)); 49 } else { 50 51 cell = row.getCell(j).toString(); 52 } 53 System.out.print(cell + "\t"); 54 } 55 System.out.println(""); 56 } 57 } 58 59 public static void main(String[] args) { 60 String fileName = "D:\\user.xlsx"; 61 File file = new File(fileName); 62 InputStream fileInpuStream = null; 63 try { 64 fileInpuStream = new FileInputStream(file); 65 } catch (FileNotFoundException e) { 66 // TODO Auto-generated catch block 67 e.printStackTrace(); 68 } 69 // 检测代码 70 try { 71 ExcelRead er = new ExcelRead(); 72 // 读取excel2007 73 er.testPoiExcel2007(fileInpuStream); 74 } catch (Exception ex) { 75 Logger.getLogger(ExcelRead.class.getName()).log(Level.SEVERE, null, 76 ex); 77 }finally{ 78 try { 79 fileInpuStream.close(); 80 } catch (IOException e) { 81 // TODO Auto-generated catch block 82 e.printStackTrace(); 83 } 84 } 85 } 86 }
表格如下:两列,第一列姓名,第二列手机号码
username | userphone |
wang | 13270893332 |
zhang | 15651892525 |
song | 15651236542 |
控制台输出:
username userphone
wang 13270893332
zhang 15651892525
song 15651236542
有些东西不是你不会,而是你不知道还有其他解决方案