CopyExcelSheetToAnotherExcelSheet.java 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. package cn.com.lzt.personnelbasearchivesmanage.util;
  2. import oracle.sql.NUMBER;
  3. import org.apache.poi.hssf.usermodel.*;
  4. import org.apache.poi.ss.usermodel.Cell;
  5. import org.apache.poi.ss.usermodel.CellStyle;
  6. import org.apache.poi.ss.util.CellRangeAddress;
  7. import java.io.*;
  8. import java.text.DecimalFormat;
  9. import java.text.SimpleDateFormat;
  10. import java.util.ArrayList;
  11. import java.util.Date;
  12. import java.util.List;
  13. import java.util.regex.Matcher;
  14. import java.util.regex.Pattern;
  15. public class CopyExcelSheetToAnotherExcelSheet {
  16. /**
  17. * 创建新的Excel并复制sheet
  18. *
  19. * @param args
  20. * @author zbw
  21. * 2017-12-18
  22. */
  23. public static void main(String[] args) {
  24. String fromPath = "F:/员工基本档案列表.xls";// excel存放路径
  25. String fileUUID = java.util.UUID.randomUUID().toString().replace("-", "");
  26. String toPathPart = "F:/upFiles";// 保存新EXCEL路径
  27. String toPath = toPathPart + "/zbwImportTemp/" + fileUUID + "/";// 保存新EXCEL路径
  28. // CopyExcelSheetToAnotherExcelSheet(fromPath,toPathPart,toPath);
  29. }
  30. public static List<String> CopyExcelSheetToAnotherExcelSheet(InputStream inputStream,
  31. String toPathPart, String toPath) {
  32. /*String fromPath = "F:/员工基本档案列表.xls";// excel存放路径
  33. String fileUUID=GetUUID.generate();
  34. String toPathPart = "F:/upFiles/zbwImportTemp/";// 保存新EXCEL路径
  35. String toPath = "F:/upFiles/zbwImportTemp/"+fileUUID+"/";// 保存新EXCEL路径
  36. System.out.println(fileUUID);*/
  37. List<String> list = new ArrayList<String>();
  38. // 新的excel 文件名
  39. String excelName = "";
  40. // File file = new File(fromPath);
  41. HSSFWorkbook wb = null;
  42. try {
  43. // InputStream in = new FileInputStream(file);
  44. wb = new HSSFWorkbook(inputStream);
  45. } catch (IOException e) {
  46. // TODO Auto-generated catch block
  47. e.printStackTrace();
  48. }
  49. for (int i = 0; i < wb.getNumberOfSheets(); i++) {//sheet
  50. HSSFSheet sheet = wb.getSheetAt(i);
  51. excelName = sheet.getSheetName();
  52. list.add(excelName);
  53. // 创建新的excel
  54. HSSFWorkbook wbCreat = new HSSFWorkbook();
  55. HSSFSheet sheetCreat = wbCreat.createSheet(sheet.getSheetName());
  56. // 复制源表中的合并单元格
  57. MergerRegion(sheetCreat, sheet);
  58. for (int k = 0; k < sheet.getPhysicalNumberOfRows(); k++) {//row
  59. // 取得源有excel Sheet的行
  60. HSSFRow row = sheet.getRow(k);
  61. // 创建新建excel Sheet的行
  62. HSSFRow rowCreat = sheetCreat.createRow(k);
  63. // 单元格式样
  64. for (int j = 0; j < row.getPhysicalNumberOfCells(); j++) {//cell
  65. // System.out.print(row.getCell(j)+"\t");
  66. // 自动适应列宽 貌似不起作用
  67. //sheetCreat.autoSizeColumn(j);
  68. rowCreat.createCell(j);
  69. String strVal = "";
  70. if (row.getCell(j) != null && row.getCell(j).toString().length() > 0) {
  71. String myCell = parseExcel(row.getCell(j));
  72. // row.getCell(j).setCellType(Cell.CELL_TYPE_STRING);
  73. // strVal = removeInternalBlank(row.getCell(j).getStringCellValue());
  74. strVal = myCell;
  75. }
  76. rowCreat.getCell(j).setCellValue(strVal);
  77. }
  78. }
  79. // System.out.println();
  80. File fileVal = new File(toPath);
  81. //如果文件夹不存在则创建
  82. if (!fileVal.exists() && !fileVal.isDirectory()) {
  83. // System.out.println("//不存在");
  84. File fileVal2 = new File(toPathPart);
  85. if (!fileVal2.exists() && !fileVal2.isDirectory()) {
  86. fileVal.mkdirs();
  87. } else {
  88. fileVal.mkdir();
  89. }
  90. } else {
  91. // System.out.println("//目录存在");
  92. }
  93. FileOutputStream fileOut = null;
  94. try {
  95. fileOut = new FileOutputStream(toPath + excelName + ".xls");
  96. } catch (FileNotFoundException e1) {
  97. // TODO Auto-generated catch block
  98. e1.printStackTrace();
  99. }
  100. try {
  101. wbCreat.write(fileOut);
  102. fileOut.close();
  103. } catch (IOException e) {
  104. // TODO Auto-generated catch block
  105. e.printStackTrace();
  106. }
  107. }
  108. return list;
  109. }
  110. /**
  111. * 复制原有sheet的合并单元格到新创建的sheet
  112. *
  113. * @param sheetCreat 新创建sheet
  114. * @param sheet 原有的sheet
  115. */
  116. private static void MergerRegion(HSSFSheet sheetCreat, HSSFSheet sheet) {
  117. int sheetMergerCount = sheet.getNumMergedRegions();
  118. for (int i = 0; i < sheetMergerCount; i++) {
  119. // Region mergedRegionAt = sheet.getMergedRegionAt(i);
  120. CellRangeAddress mergedRegionAt = sheet.getMergedRegion(i);
  121. sheetCreat.addMergedRegion(mergedRegionAt);
  122. }
  123. }
  124. /**
  125. * 去除字符串内部空格
  126. */
  127. public static String removeInternalBlank(String s) {
  128. // System.out.println("bb:" + s);
  129. Pattern p = Pattern.compile("\\s*|\t|\r|\n");
  130. Matcher m = p.matcher(s);
  131. String after = m.replaceAll("");
  132. return after;
  133. /*char str[] = s.toCharArray();
  134. StringBuffer sb = new StringBuffer();
  135. for (int i = 0; i < str.length; i++) {
  136. if (str[i] == ' ') {
  137. sb.append(' ');
  138. } else {
  139. break;
  140. }
  141. }
  142. String after = m.replaceAll("");
  143. return sb.toString() + after;*/
  144. }
  145. /**
  146. * cell格式转string
  147. *
  148. * @param cell
  149. * @return
  150. * @author zbw
  151. * 2017-12-18
  152. */
  153. public static String parseExcel(Cell cell) {
  154. if (cell == null) {
  155. return null;
  156. }
  157. String result = new String();
  158. switch (cell.getCellType()) {
  159. // case HSSFCell.CELL_TYPE_NUMERIC:// 数字类型
  160. case NUMERIC:// 数字类型
  161. if (HSSFDateUtil.isCellDateFormatted(cell)) {// 处理日期格式、时间格式
  162. SimpleDateFormat sdf = null;
  163. if (cell.getCellStyle().getDataFormat() == HSSFDataFormat
  164. .getBuiltinFormat("h:mm")) {
  165. sdf = new SimpleDateFormat("HH:mm");
  166. } else {// 日期
  167. sdf = new SimpleDateFormat("yyyy-MM-dd");
  168. }
  169. Date date = cell.getDateCellValue();
  170. result = sdf.format(date);
  171. } else if (cell.getCellStyle().getDataFormat() == 58) {
  172. // 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58)
  173. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  174. double value = cell.getNumericCellValue();
  175. Date date = org.apache.poi.ss.usermodel.DateUtil
  176. .getJavaDate(value);
  177. result = sdf.format(date);
  178. } else {
  179. double value = cell.getNumericCellValue();
  180. CellStyle style = cell.getCellStyle();
  181. DecimalFormat format = new DecimalFormat();
  182. String temp = style.getDataFormatString();
  183. // 单元格设置成常规
  184. if (temp.equals("General")) {
  185. format.applyPattern("#");
  186. }
  187. result = format.format(value);
  188. }
  189. break;
  190. // case HSSFCell.CELL_TYPE_STRING:// String类型
  191. case STRING:// String类型
  192. result = cell.getRichStringCellValue().toString();
  193. break;
  194. // case HSSFCell.CELL_TYPE_BLANK:
  195. case BLANK:
  196. result = "";
  197. default:
  198. result = "";
  199. break;
  200. }
  201. result = removeInternalBlank(result);
  202. return result;
  203. }
  204. /**
  205. * 使用poi解析需要导入的Excel
  206. *
  207. * @param inputStream
  208. * @throws Exception
  209. * @author zbw
  210. * 2017-12-16
  211. */
  212. public static void showExcel(InputStream inputStream) throws Exception {
  213. // HSSFWorkbook workbook=new HSSFWorkbook(new FileInputStream(new File(filePath)));
  214. HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
  215. HSSFSheet sheet = null;
  216. for (int i = 0; i < workbook.getNumberOfSheets(); i++) {//获取每个Sheet表
  217. sheet = workbook.getSheetAt(i);
  218. for (int j = 0; j < sheet.getPhysicalNumberOfRows(); j++) {//获取每行
  219. HSSFRow row = sheet.getRow(j);
  220. for (int k = 0; k < row.getPhysicalNumberOfCells(); k++) {//获取每个单元格
  221. // System.out.print(row.getCell(k)+"\t");
  222. }
  223. // System.out.println("---Sheet表"+i+"处理完毕---");
  224. }
  225. }
  226. }
  227. }