程序代码如下:
public class Main {
public static void main(String[] args) {
try {
InputStream fis1 = new FileInputStream("D:/fei/testfiles/2G囤卡量.xls");
InputStream fis2 = new FileInputStream("D:/fei/testfiles/电子渠道.xls");
Workbook wb1 = Workbook.getWorkbook(fis1);
Workbook wb2 = Workbook.getWorkbook(fis2);
WritableWorkbook newWb = Workbook.createWorkbook(new File("D:/fei/testfile/jxl.xls"));
newWb.importSheet("NewSheet0", 0, wb1.getSheet(0));
newWb.importSheet("NewSheet1", 1, wb2.getSheet(0));
fis1.close();
fis2.close();
wb1.close();
wb2.close();
newWb.write();
newWb.close();
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
}
合并使用的excel源文件是用杰表报表工具生成的报表。合并之后的excel文件,数据、单元格合并、边框等都与源文件相符,但是颜色会出现异常,一些单元格会加上蓝色的背景色。
我自己也新建了几个excel文件来测试,颜色不会出现异常。我不知道是office版本的问题,还是excel文件本身有什么属性是我不知道的。
以上所有的excel文件都是97-03版的xls文件。
请赐教。
pom:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.2</version>
</dependency>
导出:
public class PoiCreateExcel {
public static void main(String[] args) {
// 创建表头
String[] title = {"id","name","sex"};
//创建Excel工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
//创建一个工作表sheet
HSSFSheet sheet = workbook.createSheet();
//创建第一行
HSSFRow row = sheet.createRow(0);
HSSFCell cell = null;
// 插入第一行
for (int i = 0; i < title.length; i++) {
cell = row.createCell(i);
cell.setCellValue(title[i]);
}
// 追加数据
for (int i = 1; i < 10; i++) {// 这里的int 起始是1 也就是第二行开始
HSSFRow nexTrow = sheet.createRow(i);
HSSFCell cell2 = nexTrow.createCell(0);
cell2.setCellValue("a"+i);
cell2 = nexTrow.createCell(1);
cell2.setCellValue("user");
cell2 = nexTrow.createCell(2);
cell2.setCellValue("男");
}
// 创建一个文件
File file = new File("d:/poi.xls");
try {
file.createNewFile();
// 将内容存盘
FileOutputStream stream = FileUtils.openOutputStream(file);
workbook.write(stream);
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
导入:
public class PoiReadExcel {
public static void main(String[] args) {
// 引入需要解析的文件
File file = new File("d:/poi.xls");
try {
// 创建Excel 读取文件内容
HSSFWorkbook workbook = new HSSFWorkbook(FileUtils.openInputStream(file));
/**
* 第一种方式读取Sheet页
*/
// HSSFSheet sheet = workbook.getSheet("Sheet0");
/**
* 第二种方式读取Sheet页
*/
HSSFSheet sheet = workbook.getSheetAt(0);
int firstRowNum = 0;// 起始行第0行
int lasrRowNum = sheet.getLastRowNum();// 一直读到最后一行
for (int i = 0; i < lasrRowNum; i++) {
HSSFRow row = sheet.getRow(i);
// 获取当前最后单元格列号
int lastCellNum = row.getLastCellNum();
for (int j = 0; j < lastCellNum; j++) {
HSSFCell cell = row.getCell(j);
String value = cell.getStringCellValue();// 注意! 如果Excel 里面的值是String 那么getStringCellValue 如果是其他类型 则需要修改
System.out.print(value + " ");
}
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}