收集了一些对博主有帮助的博文,如下
>>>>>>>>>>>第一部分:
首先,mavn导入jar包
org.apache.poi
poi
3.11
org.apache.poi
poi-ooxml
3.11
org.apache.poi
poi-ooxml-schemas
3.11
stax
stax-api
1.0.1
org.apache.xmlbeans
xmlbeans
2.6.0
其次,代码如下:
package excel;
import java.io.File;
import java.io.IOException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.util.CellRangeAddress;
import org.junit.Test;
/**
*
* @author wcyong
*
* @date 2013-6-21
*/
public class TestReadMergeRegionExcel {
@Test
public void testReadExcel() {
readExcelToObj("C:\\Users\\Administrator\\Desktop\\11.xls");
}
/**
* 读取excel数据
* @param path
*/
private void readExcelToObj(String path) {
Workbook wb = null;
try {
wb = WorkbookFactory.create(new File(path));
readExcel(wb, 0, 0, 0);
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 读取excel文件
* @param wb
* @param sheetIndex sheet页下标:从0开始
* @param startReadLine 开始读取的行:从0开始
* @param tailLine 去除最后读取的行
*/
private void readExcel(Workbook wb,int sheetIndex, int startReadLine, int tailLine) {
Sheet sheet = wb.getSheetAt(sheetIndex);
Row row = null;
for(int i=startReadLine; i
row = sheet.getRow(i);
for(Cell c : row) {
c.setCellType(Cell.CELL_TYPE_STRING);
boolean isMerge = isMergedRegion(sheet, i, c.getColumnIndex());
//判断是否具有合并单元格
if(isMerge) {
String rs = getMergedRegionValue(sheet, row.getRowNum(), c.getColumnIndex());
System.out.print(rs + " ");
}else {
System.out.print(c.getRichStringCellValue()+" ");
}
}
System.out.println();
}
}
/**
* 获取合并单元格的值
* @param sheet
* @param row
* @param column
* @return
*/
public String getMergedRegionValue(Sheet sheet ,int row , int column){
int sheetMergeCount = sheet.getNumMergedRegions();
for(int i = 0 ; i < sheetMergeCount ; i++){
CellRangeAddress ca = sheet.getMergedRegion(i);
int firstColumn = ca.getFirstColumn();
int lastColumn = ca.getLastColumn();
int firstRow = ca.getFirstRow();
int lastRow = ca.getLastRow();
if(row >= firstRow && row <= lastRow){
if(column >= firstColumn && column <= lastColumn){
Row fRow = sheet.getRow(firstRow);
Cell fCell = fRow.getCell(firstColumn);
return getCellValue(fCell) ;
}
}
}
return null ;
}
/**
* 判断合并了行
* @param sheet
* @param row
* @param column
* @return
*/
private boolean isMergedRow(Sheet sheet,int row ,int column) {
int sheetMergeCount = sheet.getNumMergedRegions();
for (int i = 0; i < sheetMergeCount; i++