Java读取excel

  1 import java.io.BufferedInputStream;
  2 import java.io.File;
  3 import java.io.FileInputStream;
  4 import java.io.FileNotFoundException;
  5 import java.io.IOException;
  6 import java.text.DecimalFormat;
  7 import java.text.SimpleDateFormat;
  8 import java.util.ArrayList;
  9 import java.util.Arrays;
 10 import java.util.Date;
 11 import java.util.LinkedHashMap;
 12 import java.util.List;
 13 import java.util.Map;
 14 import java.util.Map.Entry;
 15 
 16 import org.apache.poi.hssf.usermodel.HSSFCell;
 17 import org.apache.poi.hssf.usermodel.HSSFDateUtil;
 18 import org.apache.poi.xssf.usermodel.XSSFCell;
 19 import org.apache.poi.xssf.usermodel.XSSFRow;
 20 import org.apache.poi.xssf.usermodel.XSSFSheet;
 21 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 22 
 23 public class rex {
 24 
 25     public static void main(String[] args) throws Exception {
 26         Map<Object, Object> map = new LinkedHashMap<Object, Object>();
 27         String s = "C:\\Users\\Lenovo\\Desktop\\文档\\test.xls";
 28         File file = new File(s);
 29         String[][] result = getData(file, 1);
 30         int rowLength = result.length;
 31         System.out.println("..." + rowLength);
 32         for (int i = 0; i < rowLength; i++) {
 33             map.put(result[i][0], new String[] { result[i][1], result[i][2] });
 34             System.out.println(result[i][0] + result[i][1] + result[i][2]);
 35         }
 36 //        net.sf.json.JSONObject jo = net.sf.json.JSONObject.fromObject(map);
 37 //        Map<Object, Object> m = jo;
 38 //        for (Entry<Object, Object> mp : m.entrySet()) {
 39 //            System.out.println(mp.getKey() + ":" + mp.getValue().toString());
 40 //        }
 41 
 42     }
 43 
 44     /**
 45      * 
 46      * 读取Excel的内容,第一维数组存储的是一行中格列的值,二维数组存储的是多少个行
 47      * 
 48      * @param file       读取数据的源Excel
 49      * 
 50      * @param ignoreRows 读取数据忽略的行数,比喻行头不需要读入 忽略的行数为1
 51      * 
 52      * @return 读出的Excel中数据的内容
 53      * 
 54      * @throws FileNotFoundException
 55      * 
 56      * @throws IOException
 57      * 
 58      */
 59 
 60     public static String[][] getData(File file, int ignoreRows)
 61 
 62             throws FileNotFoundException, IOException {
 63 
 64         List<String[]> result = new ArrayList<String[]>();
 65         int rowSize = 0;
 66         BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
 67 //           POIFSFileSystem fs = new POIFSFileSystem(in);
 68         XSSFWorkbook wb = new XSSFWorkbook(in);
 69         XSSFCell cell = null;
 70         for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) {
 71             XSSFSheet st = wb.getSheetAt(sheetIndex);
 72             // 第一行为标题,不取
 73             for (int rowIndex = ignoreRows; rowIndex <= st.getLastRowNum(); rowIndex++) {
 74                 XSSFRow row = st.getRow(rowIndex);
 75                 if (row == null) {
 76                     continue;
 77                 }
 78 
 79                 int tempRowSize = row.getLastCellNum() + 1;
 80                 if (tempRowSize > rowSize) {
 81                     rowSize = tempRowSize;
 82                 }
 83 
 84                 String[] values = new String[rowSize];
 85                 Arrays.fill(values, "");
 86                 boolean hasValue = false;
 87                 for (short columnIndex = 0; columnIndex <= row.getLastCellNum(); columnIndex++) {
 88                     String value = "";
 89                     cell = row.getCell(columnIndex);
 90                     if (cell != null) {
 91                         // 注意:一定要设成这个,否则可能会出现乱码
 92 //                         cell.setEncoding(HSSFCell.ENCODING_UTF_16);
 93                         switch (cell.getCellType()) {
 94                         case HSSFCell.CELL_TYPE_STRING:
 95                             value = cell.getStringCellValue();
 96                             break;
 97                         case HSSFCell.CELL_TYPE_NUMERIC:
 98                             if (HSSFDateUtil.isCellDateFormatted(cell)) {
 99                                 Date date = cell.getDateCellValue();
100                                 if (date != null) {
101                                     value = new SimpleDateFormat("yyyy-MM-dd")
102                                             .format(date);
103                                 } else {
104                                     value = "";
105                                 }
106                             } else {
107                                 value = new DecimalFormat("0").format(cell.getNumericCellValue());
108                             }
109                             break;
110                         case HSSFCell.CELL_TYPE_FORMULA:
111                             // 导入时如果为公式生成的数据则无值
112                             if (!cell.getStringCellValue().equals("")) {
113                                 value = cell.getStringCellValue();
114                             } else {
115                                 value = cell.getNumericCellValue() + "";
116                             }
117                             break;
118                         case HSSFCell.CELL_TYPE_BLANK:
119                             break;
120                         case HSSFCell.CELL_TYPE_ERROR:
121                             value = "";
122                             break;
123                         case HSSFCell.CELL_TYPE_BOOLEAN:
124                             value = (cell.getBooleanCellValue() == true ? "Y" : "N");
125                             break;
126                         default:
127                             value = "";
128                         }
129                     }
130 
131                     if (columnIndex == 0 && value.trim().equals("")) {
132                         break;
133                     }
134 
135                     values[columnIndex] = rightTrim(value);
136                     hasValue = true;
137                 }
138 
139                 if (hasValue) {
140                     result.add(values);
141                 }
142 
143             }
144 
145         }
146 
147         in.close();
148         String[][] returnArray = new String[result.size()][rowSize];
149         for (int i = 0; i < returnArray.length; i++) {
150             returnArray[i] = (String[]) result.get(i);
151         }
152         return returnArray;
153 
154     }
155 
156     /**
157      * 
158      * 去掉字符串右边的空格
159      * 
160      * @param str 要处理的字符串
161      * 
162      * @return 处理后的字符串
163      * 
164      */
165 
166     public static String rightTrim(String str) {
167 
168         if (str == null) {
169             return "";
170         }
171 
172         int length = str.length();
173         for (int i = length - 1; i >= 0; i--) {
174             if (str.charAt(i) != 0x20) {
175                 break;
176             }
177             length--;
178         }
179         return str.substring(0, length);
180     }
181 
182 }

 

posted @ 2019-07-24 18:05  happy老家  阅读(456)  评论(0编辑  收藏  举报