我被分配了一个作业,我需要拆分电子表格的数据并将其写入新的电子表格。条件是,给定电子表格可能有多个合并单元格,我需要找到这些合并单元格并将这些数据写入新电子表格。即,一个合并单元格到另一个合并单元格之间的数据或单元格必须写入另一个电子表格。
我的努力守则如下,
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class CopyTest {
public static void main(String[] args) throws IOException {
CopyTest excel = new CopyTest();
excel.process("D:\\B3.xls");
}
public void process(String fileName) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fileName));
HSSFWorkbook workbook = new HSSFWorkbook(bis);
HSSFWorkbook myWorkBook = new HSSFWorkbook();
HSSFSheet sheet = null;
HSSFRow row = null;
HSSFCell cell = null;
HSSFSheet mySheet = null;
HSSFRow myRow = null;
HSSFCell myCell = null;
int sheets = workbook.getNumberOfSheets();
int fCell = 0;
int lCell = 0;
int fRow = 0;
int lRow = 0;
for (int iSheet = 0; iSheet < sheets; iSheet++) {
sheet = workbook.getSheetAt(iSheet);
if (sheet != null) {
mySheet = myWorkBook.createSheet(sheet.getSheetName());
fRow = sheet.getFirstRowNum();
System.out.println("First Row at"+fRow);
lRow = sheet.getLastRowNum();
for (int iRow = fRow; iRow <= lRow; iRow++) {
row = sheet.getRow(iRow);
myRow = mySheet.createRow(iRow);
if (row != null) {
fCell = row.getFirstCellNum();
lCell = row.getLastCellNum();
for (int iCell = fCell; iCell < lCell; iCell++) {
//if (mySheet.getMergedRegionAt(index)!=null)
System.out.println("Finding next merged Cells");
cell = row.getCell(iCell);
myCell = myRow.createCell(iCell);
if (cell != null) {
myCell.setCellType(cell.getCellType());
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_BLANK:
myCell.setCellValue("");
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
myCell.setCellValue(cell.getBooleanCellValue());
break;
case HSSFCell.CELL_TYPE_ERROR:
myCell.setCellErrorValue(cell.getErrorCellValue());
break;
case HSSFCell.CELL_TYPE_FORMULA:
myCell.setCellFormula(cell.getCellFormula());
break;
case HSSFCell.CELL_TYPE_NUMERIC:
myCell.setCellValue(cell.getNumericCellValue());
break;
case HSSFCell.CELL_TYPE_STRING:
myCell.setCellValue(cell.getStringCellValue());
break;
default:
myCell.setCellFormula(cell.getCellFormula());
// System.out.println("Reading Cell value\t"+myCell);
}System.out.println("Reading Cell value\t"+myCell);
}
}
}
}
}
}
bis.close();
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream("D:\\Result Excel1.xls", true));
myWorkBook.write(bos);
bos.close();
}}
使用此代码,我已将电子表格克隆到另一个新工作表中。在这里,我找不到合并的单元格,getMergedCellRegionAt() 帮助我并返回像 A:4 D:12 这样的合并单元格区域。我该怎么做。请帮助我,感谢您的微小努力。提前致谢。