java 复制excel_java 实现 excel sheet 拷贝到另一个Excel文件中 poi

时间:2025-03-10 13:22:48

public class CopyExcelSheetToAnotherExcelSheet {

public static void main(String[] args) throws FileNotFoundException, IOException {

String fromPath = "D:\\share\\jiemu_new\\";// excel存放路径

String toPath = "c:\\ok\\";// 保存新EXCEL路径

// 新的excel 文件名

String excelName = "节目访问量";

// 创建新的excel

HSSFWorkbook wbCreat = new HSSFWorkbook();

File file = new File(fromPath);

for (File excel : ()) {

// 打开已有的excel

String strExcelPath = fromPath + "\\" + ();

InputStream in = new FileInputStream(strExcelPath);

HSSFWorkbook wb = new HSSFWorkbook(in);

for (int ii = 0; ii < (); ii++) {

HSSFSheet sheet = (ii);

HSSFSheet sheetCreat = (());

// 复制源表中的合并单元格

MergerRegion(sheetCreat, sheet);

int firstRow = ();

int lastRow = ();

for (int i = firstRow; i <= lastRow; i++) {

// 创建新建excel Sheet的行

HSSFRow rowCreat = (i);

// 取得源有excel Sheet的行

HSSFRow row = (i);

// 单元格式样

int firstCell = ();

int lastCell = ();

for (int j = firstCell; j < lastCell; j++) {

// 自动适应列宽 貌似不起作用

//(j);

((j));

(j);

String strVal ="";

if ((j)==null) {

}else{

strVal = removeInternalBlank((j).getStringCellValue());

}

(j).setCellValue(strVal);

}

}

}

}

FileOutputStream fileOut = new FileOutputStream(toPath + excelName + ".xls");

(fileOut);

();

}

/**

* 复制原有sheet的合并单元格到新创建的sheet

*

* @param sheetCreat

*  新创建sheet

* @param sheet

*  原有的sheet

*/

private static void MergerRegion(HSSFSheet sheetCreat, HSSFSheet sheet) {

int sheetMergerCount = ();

for (int i = 0; i < sheetMergerCount; i++) {

Region mergedRegionAt = (i);

(mergedRegionAt);

}

}

/**

* 去除字符串内部空格

*/

public static String removeInternalBlank(String s) {

// ("bb:" + s);

Pattern p = ("\\s*|\t|\r|\n");

Matcher m = (s);

char str[] = ();

StringBuffer sb = new StringBuffer();

for (int i = 0; i < ; i++) {

if (str[i] == ' ') {

(' ');

} else {

break;

}

}

String after = ("");

return () + after;

}

}