ExcelUtil.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. package nc.pub.toos.FileTool;
  2. import java.io.BufferedReader;
  3. import java.io.BufferedWriter;
  4. import java.io.ByteArrayOutputStream;
  5. import java.io.File;
  6. import java.io.FileInputStream;
  7. import java.io.FileNotFoundException;
  8. import java.io.FileOutputStream;
  9. import java.io.IOException;
  10. import java.io.InputStream;
  11. import java.io.InputStreamReader;
  12. import java.io.OutputStream;
  13. import java.io.OutputStreamWriter;
  14. import java.math.BigDecimal;
  15. import java.text.DecimalFormat;
  16. import java.text.SimpleDateFormat;
  17. import java.util.ArrayList;
  18. import java.util.Date;
  19. import java.util.List;
  20. import org.apache.poi.hssf.usermodel.HSSFCell;
  21. import org.apache.poi.hssf.usermodel.HSSFRow;
  22. import org.apache.poi.hssf.usermodel.HSSFSheet;
  23. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  24. import org.apache.poi.ss.usermodel.CellType;
  25. import org.apache.poi.ss.usermodel.DateUtil;
  26. import org.apache.poi.xssf.usermodel.XSSFCell;
  27. import org.apache.poi.xssf.usermodel.XSSFRow;
  28. import org.apache.poi.xssf.usermodel.XSSFSheet;
  29. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  30. import nc.vo.pubapp.pattern.exception.ExceptionUtils;
  31. public class ExcelUtil {
  32. //默认单元格内容为数字时格式
  33. private static DecimalFormat df = new DecimalFormat("0");
  34. // 默认单元格格式化日期字符串
  35. private static SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
  36. // 格式化数字
  37. private static DecimalFormat nf = new DecimalFormat("0.00");
  38. public static ArrayList<ArrayList<Object>> readFile(File file){
  39. if(file == null){
  40. return null;
  41. }
  42. String filename = file.getName().toLowerCase();
  43. if(filename.endsWith("xlsx")){
  44. //处理ecxel2007
  45. try {
  46. return readExcel2007(new FileInputStream(file));
  47. } catch (FileNotFoundException e) {
  48. // TODO Auto-generated catch block
  49. return null;
  50. }
  51. }else if(filename.endsWith("xls")){
  52. //处理ecxel2003
  53. try {
  54. return readExcel2003(new FileInputStream(file));
  55. } catch (FileNotFoundException e) {
  56. // TODO Auto-generated catch block
  57. return null;
  58. }
  59. }else if(filename.endsWith("csv")) {
  60. try {
  61. return readCsv(new FileInputStream(file));
  62. } catch (FileNotFoundException e) {
  63. // TODO Auto-generated catch block
  64. return null;
  65. }
  66. }else {
  67. ExceptionUtils.wrappBusinessException("导入失败,系统只接收xls,xlsx,csv类型文件");
  68. return null;
  69. }
  70. }
  71. /*
  72. * @return 将返回结果存储在ArrayList内,存储结构与二位数组类似
  73. * lists.get(0).get(0)表示过去Excel中0行0列单元格
  74. */
  75. public static ArrayList<ArrayList<Object>> readExcel2003(InputStream input){
  76. try{
  77. ArrayList<ArrayList<Object>> rowList = new ArrayList<ArrayList<Object>>();
  78. ArrayList<Object> colList;
  79. HSSFWorkbook wb = new HSSFWorkbook(input);
  80. HSSFSheet sheet = wb.getSheetAt(0);
  81. HSSFRow row;
  82. HSSFCell cell;
  83. Object value = null;
  84. for(int i = sheet.getFirstRowNum() , rowCount = 0; rowCount < sheet.getPhysicalNumberOfRows() ; i++ ){
  85. row = sheet.getRow(i);
  86. colList = new ArrayList<Object>();
  87. if(row == null){
  88. //当读取行为空时
  89. if(i != sheet.getPhysicalNumberOfRows()){//判断是否是最后一行
  90. rowList.add(colList);
  91. }
  92. continue;
  93. }else{
  94. rowCount++;
  95. }
  96. for( int j = row.getFirstCellNum() ; j <= row.getLastCellNum() ;j++){
  97. cell = row.getCell(j);
  98. if(cell == null || cell.getCellType() == CellType.BLANK){
  99. //当该单元格为空
  100. if(j != row.getLastCellNum()){//判断是否是该行中最后一个单元格
  101. colList.add("");
  102. }
  103. continue;
  104. }
  105. switch(cell.getCellType()){
  106. case STRING:
  107. value = cell.getStringCellValue().trim();
  108. break;
  109. case NUMERIC:
  110. short format = cell.getCellStyle().getDataFormat();
  111. if (DateUtil.isCellDateFormatted(cell)) {
  112. SimpleDateFormat sdf = null;
  113. //System.out.println("cell.getCellStyle().getDataFormat()="+cell.getCellStyle().getDataFormat());
  114. if (format == 20 || format == 32) {
  115. sdf = new SimpleDateFormat("HH:mm");
  116. } else if (format == 14 || format == 31 || format == 57 || format == 58) {
  117. // 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58)
  118. sdf = new SimpleDateFormat("yyyy-MM-dd");
  119. double celvalue = cell.getNumericCellValue();
  120. Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(celvalue);
  121. value = sdf.format(date);
  122. }else {// 日期
  123. sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  124. }
  125. try {
  126. value = sdf.format(cell.getDateCellValue());// 日期
  127. } catch (Exception e) {
  128. try {
  129. throw new Exception("exception on get date data !".concat(e.toString()));
  130. } catch (Exception e1) {
  131. e1.printStackTrace();
  132. }
  133. }finally{
  134. sdf = null;
  135. }
  136. } else {
  137. // BigDecimal bd = new BigDecimal(cell.getNumericCellValue());
  138. value = cell.toString().trim();// 数值 这种用BigDecimal包装再获取plainString,可以防止获取到科学计数值
  139. }
  140. break;
  141. case BOOLEAN:
  142. value = Boolean.valueOf(cell.getBooleanCellValue());
  143. break;
  144. case BLANK:
  145. value = "";
  146. break;
  147. default:
  148. value = cell.toString().trim();
  149. }// end switch
  150. colList.add(value);
  151. }//end for j
  152. rowList.add(colList);
  153. }//end for i
  154. return rowList;
  155. }catch(Exception e){
  156. return null;
  157. }
  158. }
  159. public static ArrayList<ArrayList<Object>> readExcel2007(InputStream input){
  160. try{
  161. ArrayList<ArrayList<Object>> rowList = new ArrayList<ArrayList<Object>>();
  162. ArrayList<Object> colList;
  163. XSSFWorkbook wb = new XSSFWorkbook(input);
  164. XSSFSheet sheet = wb.getSheetAt(0);
  165. XSSFRow row;
  166. XSSFCell cell;
  167. Object value = null;
  168. for(int i = sheet.getFirstRowNum() , rowCount = 0; rowCount < sheet.getPhysicalNumberOfRows() ; i++ ){
  169. row = sheet.getRow(i);
  170. colList = new ArrayList<Object>();
  171. if(row == null){
  172. //当读取行为空时
  173. if(i != sheet.getPhysicalNumberOfRows()){//判断是否是最后一行
  174. rowList.add(colList);
  175. }
  176. continue;
  177. }else{
  178. rowCount++;
  179. }
  180. for( int j = row.getFirstCellNum() ; j <= row.getLastCellNum() ;j++){
  181. cell = row.getCell(j);
  182. if(cell == null || cell.getCellType() == CellType.BLANK){
  183. //当该单元格为空
  184. if(j != row.getLastCellNum()){//判断是否是该行中最后一个单元格
  185. colList.add("");
  186. }
  187. continue;
  188. }
  189. switch(cell.getCellType()){
  190. case STRING:
  191. value = cell.getStringCellValue().trim();
  192. break;
  193. case NUMERIC:
  194. short format = cell.getCellStyle().getDataFormat();
  195. if (DateUtil.isCellDateFormatted(cell)) {
  196. SimpleDateFormat sdf = null;
  197. //System.out.println("cell.getCellStyle().getDataFormat()="+cell.getCellStyle().getDataFormat());
  198. if (format == 20 || format == 32) {
  199. sdf = new SimpleDateFormat("HH:mm");
  200. } else if (format == 14 || format == 31 || format == 57 || format == 58) {
  201. // 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58)
  202. sdf = new SimpleDateFormat("yyyy-MM-dd");
  203. double celvalue = cell.getNumericCellValue();
  204. Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(celvalue);
  205. value = sdf.format(date);
  206. }else {// 日期
  207. sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  208. }
  209. try {
  210. value = sdf.format(cell.getDateCellValue());// 日期
  211. } catch (Exception e) {
  212. try {
  213. throw new Exception("exception on get date data !".concat(e.toString()));
  214. } catch (Exception e1) {
  215. e1.printStackTrace();
  216. }
  217. }finally{
  218. sdf = null;
  219. }
  220. } else {
  221. // BigDecimal bd = new BigDecimal(cell.getNumericCellValue());
  222. value = cell.toString().trim();// 数值 这种用BigDecimal包装再获取plainString,可以防止获取到科学计数值
  223. }
  224. break;
  225. case BOOLEAN:
  226. value = Boolean.valueOf(cell.getBooleanCellValue());
  227. break;
  228. case BLANK:
  229. value = "";
  230. break;
  231. default:
  232. value = cell.toString().trim();
  233. }// end switch
  234. colList.add(value);
  235. }//end for j
  236. rowList.add(colList);
  237. }//end for i
  238. return rowList;
  239. }catch(Exception e){
  240. System.out.println("exception");
  241. return null;
  242. }
  243. }
  244. public static void writeExcel(ArrayList<ArrayList<Object>> result,String path){
  245. if(result == null){
  246. return;
  247. }
  248. HSSFWorkbook wb = new HSSFWorkbook();
  249. HSSFSheet sheet = wb.createSheet("sheet1");
  250. for(int i = 0 ;i < result.size() ; i++){
  251. HSSFRow row = sheet.createRow(i);
  252. if(result.get(i) != null){
  253. for(int j = 0; j < result.get(i).size() ; j ++){
  254. HSSFCell cell = row.createCell(j);
  255. cell.setCellValue(result.get(i).get(j).toString());
  256. }
  257. }
  258. }
  259. ByteArrayOutputStream os = new ByteArrayOutputStream();
  260. try
  261. {
  262. wb.write(os);
  263. } catch (IOException e){
  264. e.printStackTrace();
  265. }
  266. byte[] content = os.toByteArray();
  267. File file = new File(path);//Excel文件生成后存储的位置。
  268. OutputStream fos = null;
  269. try
  270. {
  271. fos = new FileOutputStream(file);
  272. fos.write(content);
  273. os.close();
  274. fos.close();
  275. }catch (Exception e){
  276. e.printStackTrace();
  277. }
  278. }
  279. /**
  280. * 导出
  281. *
  282. * @param file csv文件(路径+文件名),csv文件不存在会自动创建
  283. * @param dataList 数据
  284. * @return
  285. */
  286. public static boolean exportCsv(File file, List<String> dataList){
  287. boolean isSucess=false;
  288. FileOutputStream out=null;
  289. OutputStreamWriter osw=null;
  290. BufferedWriter bw=null;
  291. try {
  292. out = new FileOutputStream(file);
  293. osw = new OutputStreamWriter(out);
  294. bw =new BufferedWriter(osw);
  295. if(dataList!=null && !dataList.isEmpty()){
  296. for(String data : dataList){
  297. bw.append(data).append("\r");
  298. }
  299. }
  300. isSucess=true;
  301. } catch (Exception e) {
  302. isSucess=false;
  303. }finally{
  304. if(bw!=null){
  305. try {
  306. bw.close();
  307. bw=null;
  308. } catch (IOException e) {
  309. e.printStackTrace();
  310. }
  311. }
  312. if(osw!=null){
  313. try {
  314. osw.close();
  315. osw=null;
  316. } catch (IOException e) {
  317. e.printStackTrace();
  318. }
  319. }
  320. if(out!=null){
  321. try {
  322. out.close();
  323. out=null;
  324. } catch (IOException e) {
  325. e.printStackTrace();
  326. }
  327. }
  328. }
  329. return isSucess;
  330. }
  331. /**
  332. * 导入
  333. *
  334. * @param input csv文件(路径+文件)
  335. * @return
  336. */
  337. public static ArrayList<ArrayList<Object>> readCsv(InputStream input){
  338. ArrayList<ArrayList<Object>> rowList = new ArrayList<ArrayList<Object>>();
  339. BufferedReader br=null;
  340. try {
  341. br = new BufferedReader(new InputStreamReader(input,"GBK"));
  342. String line = "";
  343. ArrayList<Object> colList;
  344. while ((line = br.readLine()) != null) {
  345. colList = new ArrayList<Object>();
  346. String[] datas = line.split(",");
  347. for (String data : datas) {
  348. colList.add(data);
  349. }
  350. rowList.add(colList);
  351. }
  352. }catch (Exception e) {
  353. }finally{
  354. if(br!=null){
  355. try {
  356. br.close();
  357. br=null;
  358. } catch (IOException e) {
  359. e.printStackTrace();
  360. }
  361. }
  362. }
  363. return rowList;
  364. }
  365. public static DecimalFormat getDf() {
  366. return df;
  367. }
  368. public static void setDf(DecimalFormat df) {
  369. ExcelUtil.df = df;
  370. }
  371. public static SimpleDateFormat getSdf() {
  372. return sdf;
  373. }
  374. public static void setSdf(SimpleDateFormat sdf) {
  375. ExcelUtil.sdf = sdf;
  376. }
  377. public static DecimalFormat getNf() {
  378. return nf;
  379. }
  380. public static void setNf(DecimalFormat nf) {
  381. ExcelUtil.nf = nf;
  382. }
  383. }