| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256 |
- package cn.com.lzt.personnelbasearchivesmanage.util;
- import oracle.sql.NUMBER;
- import org.apache.poi.hssf.usermodel.*;
- import org.apache.poi.ss.usermodel.Cell;
- import org.apache.poi.ss.usermodel.CellStyle;
- import org.apache.poi.ss.util.CellRangeAddress;
- import java.io.*;
- import java.text.DecimalFormat;
- import java.text.SimpleDateFormat;
- import java.util.ArrayList;
- import java.util.Date;
- import java.util.List;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- public class CopyExcelSheetToAnotherExcelSheet {
- /**
- * 创建新的Excel并复制sheet
- *
- * @param args
- * @author zbw
- * 2017-12-18
- */
- public static void main(String[] args) {
- String fromPath = "F:/员工基本档案列表.xls";// excel存放路径
- String fileUUID = java.util.UUID.randomUUID().toString().replace("-", "");
- String toPathPart = "F:/upFiles";// 保存新EXCEL路径
- String toPath = toPathPart + "/zbwImportTemp/" + fileUUID + "/";// 保存新EXCEL路径
- // CopyExcelSheetToAnotherExcelSheet(fromPath,toPathPart,toPath);
- }
- public static List<String> CopyExcelSheetToAnotherExcelSheet(InputStream inputStream,
- String toPathPart, String toPath) {
-
- /*String fromPath = "F:/员工基本档案列表.xls";// excel存放路径
- String fileUUID=GetUUID.generate();
- String toPathPart = "F:/upFiles/zbwImportTemp/";// 保存新EXCEL路径
- String toPath = "F:/upFiles/zbwImportTemp/"+fileUUID+"/";// 保存新EXCEL路径
- System.out.println(fileUUID);*/
- List<String> list = new ArrayList<String>();
- // 新的excel 文件名
- String excelName = "";
- // File file = new File(fromPath);
- HSSFWorkbook wb = null;
- try {
- // InputStream in = new FileInputStream(file);
- wb = new HSSFWorkbook(inputStream);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- for (int i = 0; i < wb.getNumberOfSheets(); i++) {//sheet
- HSSFSheet sheet = wb.getSheetAt(i);
- excelName = sheet.getSheetName();
- list.add(excelName);
- // 创建新的excel
- HSSFWorkbook wbCreat = new HSSFWorkbook();
- HSSFSheet sheetCreat = wbCreat.createSheet(sheet.getSheetName());
- // 复制源表中的合并单元格
- MergerRegion(sheetCreat, sheet);
- for (int k = 0; k < sheet.getPhysicalNumberOfRows(); k++) {//row
- // 取得源有excel Sheet的行
- HSSFRow row = sheet.getRow(k);
- // 创建新建excel Sheet的行
- HSSFRow rowCreat = sheetCreat.createRow(k);
- // 单元格式样
- for (int j = 0; j < row.getPhysicalNumberOfCells(); j++) {//cell
- // System.out.print(row.getCell(j)+"\t");
- // 自动适应列宽 貌似不起作用
- //sheetCreat.autoSizeColumn(j);
- rowCreat.createCell(j);
- String strVal = "";
- if (row.getCell(j) != null && row.getCell(j).toString().length() > 0) {
- String myCell = parseExcel(row.getCell(j));
- // row.getCell(j).setCellType(Cell.CELL_TYPE_STRING);
- // strVal = removeInternalBlank(row.getCell(j).getStringCellValue());
- strVal = myCell;
- }
- rowCreat.getCell(j).setCellValue(strVal);
- }
- }
- // System.out.println();
- File fileVal = new File(toPath);
- //如果文件夹不存在则创建
- if (!fileVal.exists() && !fileVal.isDirectory()) {
- // System.out.println("//不存在");
- File fileVal2 = new File(toPathPart);
- if (!fileVal2.exists() && !fileVal2.isDirectory()) {
- fileVal.mkdirs();
- } else {
- fileVal.mkdir();
- }
- } else {
- // System.out.println("//目录存在");
- }
- FileOutputStream fileOut = null;
- try {
- fileOut = new FileOutputStream(toPath + excelName + ".xls");
- } catch (FileNotFoundException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- try {
- wbCreat.write(fileOut);
- fileOut.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- return list;
- }
- /**
- * 复制原有sheet的合并单元格到新创建的sheet
- *
- * @param sheetCreat 新创建sheet
- * @param sheet 原有的sheet
- */
- private static void MergerRegion(HSSFSheet sheetCreat, HSSFSheet sheet) {
- int sheetMergerCount = sheet.getNumMergedRegions();
- for (int i = 0; i < sheetMergerCount; i++) {
- // Region mergedRegionAt = sheet.getMergedRegionAt(i);
- CellRangeAddress mergedRegionAt = sheet.getMergedRegion(i);
- sheetCreat.addMergedRegion(mergedRegionAt);
- }
- }
- /**
- * 去除字符串内部空格
- */
- public static String removeInternalBlank(String s) {
- // System.out.println("bb:" + s);
- Pattern p = Pattern.compile("\\s*|\t|\r|\n");
- Matcher m = p.matcher(s);
- String after = m.replaceAll("");
- return after;
- /*char str[] = s.toCharArray();
- StringBuffer sb = new StringBuffer();
- for (int i = 0; i < str.length; i++) {
- if (str[i] == ' ') {
- sb.append(' ');
- } else {
- break;
- }
- }
- String after = m.replaceAll("");
- return sb.toString() + after;*/
- }
- /**
- * cell格式转string
- *
- * @param cell
- * @return
- * @author zbw
- * 2017-12-18
- */
- public static String parseExcel(Cell cell) {
- if (cell == null) {
- return null;
- }
- String result = new String();
- switch (cell.getCellType()) {
- // case HSSFCell.CELL_TYPE_NUMERIC:// 数字类型
- case NUMERIC:// 数字类型
- if (HSSFDateUtil.isCellDateFormatted(cell)) {// 处理日期格式、时间格式
- SimpleDateFormat sdf = null;
- if (cell.getCellStyle().getDataFormat() == HSSFDataFormat
- .getBuiltinFormat("h:mm")) {
- sdf = new SimpleDateFormat("HH:mm");
- } else {// 日期
- sdf = new SimpleDateFormat("yyyy-MM-dd");
- }
- Date date = cell.getDateCellValue();
- result = sdf.format(date);
- } else if (cell.getCellStyle().getDataFormat() == 58) {
- // 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58)
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
- double value = cell.getNumericCellValue();
- Date date = org.apache.poi.ss.usermodel.DateUtil
- .getJavaDate(value);
- result = sdf.format(date);
- } else {
- double value = cell.getNumericCellValue();
- CellStyle style = cell.getCellStyle();
- DecimalFormat format = new DecimalFormat();
- String temp = style.getDataFormatString();
- // 单元格设置成常规
- if (temp.equals("General")) {
- format.applyPattern("#");
- }
- result = format.format(value);
- }
- break;
- // case HSSFCell.CELL_TYPE_STRING:// String类型
- case STRING:// String类型
- result = cell.getRichStringCellValue().toString();
- break;
- // case HSSFCell.CELL_TYPE_BLANK:
- case BLANK:
- result = "";
- default:
- result = "";
- break;
- }
- result = removeInternalBlank(result);
- return result;
- }
- /**
- * 使用poi解析需要导入的Excel
- *
- * @param inputStream
- * @throws Exception
- * @author zbw
- * 2017-12-16
- */
- public static void showExcel(InputStream inputStream) throws Exception {
- // HSSFWorkbook workbook=new HSSFWorkbook(new FileInputStream(new File(filePath)));
- HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
- HSSFSheet sheet = null;
- for (int i = 0; i < workbook.getNumberOfSheets(); i++) {//获取每个Sheet表
- sheet = workbook.getSheetAt(i);
- for (int j = 0; j < sheet.getPhysicalNumberOfRows(); j++) {//获取每行
- HSSFRow row = sheet.getRow(j);
- for (int k = 0; k < row.getPhysicalNumberOfCells(); k++) {//获取每个单元格
- // System.out.print(row.getCell(k)+"\t");
- }
- // System.out.println("---Sheet表"+i+"处理完毕---");
- }
- }
- }
- }
|