需求:需要从a.xls文件中读取一列中文数据,存放到b.xls文件中对应的列中去.
图示:a.xls中a列和b列组成数字串对应b.xls中的a列,a.xlsD列写入b.xlsB列
功能实现:
1:处理保存a中数据:
/**
* 读excel
* @param filepath
* @param sheetNum 工作簿编号0开始第一个工作簿添0,以此类推
* @throws Exception
*/
public static void readExcel(String filepath,int sheetNum) throws Exception {
InputStream inp = new FileInputStream(filepath);
POIFSFileSystem fs = new POIFSFileSystem(inp);
Workbook wb = new HSSFWorkbook(fs);
Sheet sheet = wb.getSheetAt(sheetNum);
for(int i = sheet.getFirstRowNum();i<=sheet.getLastRowNum();i++) {
Row row = sheet.getRow(i);
// 取第一个单元格
Cell cell = row.getCell(0);
String pill_preId = "";
String pill_chname = "";
if(null != cell) {
Integer cellV = (int)cell.getNumericCellValue();
pill_preId = String.format("%02d", cellV);
}
// 取第2个单元格
cell = row.getCell(1);
if(null != cell) {
Integer cellV = (int)cell.getNumericCellValue();
pill_preId = pill_preId+String.format("%02d", cellV);
}
// 取第4个单元格
cell = row.getCell(3);
if(null != cell) {
String cellV = cell.getStringCellValue();
pill_chname = cellV;
}
//保存map
System.out.println("pill_preId: "+pill_preId+" pill_chname: "+pill_chname);
pillMap.put(pill_preId, pill_chname);
}
}
2:开始插入b表格中
/**
* 写入excel
* @param filename
* @param sheetNum 工作簿编号0开始第一个工作簿添0,以此类推
* @throws Exception
*/
public static void writeExcel(String filename,int sheetNum) throws Exception {
InputStream inp = new FileInputStream(filename);
POIFSFileSystem fs = new POIFSFileSystem(inp);
Workbook wb = new HSSFWorkbook(fs);
Sheet sheet = wb.getSheetAt(sheetNum);
for(int i = sheet.getFirstRowNum();i<=sheet.getLastRowNum();i++) {
Row row = sheet.getRow(i);
// 取第一个单元格
Cell cell = row.getCell(0);
if(null == cell) {
continue;
}
String cellV = cell.getStringCellValue();
String newV = pillMap.get(cellV);
//写入第二个单元格
if(newV != null && !newV.isEmpty()) {
Cell cell1 = row.getCell(1);
if(null == cell1) {
row.createCell(1);
}
cell1.setCellType(CellType.STRING);
cell1.setCellValue(newV);
}
}
FileOutputStream fileOut = new FileOutputStream(filename);
wb.write(fileOut);
fileOut.close();
}
3:单元测试:
private static Map<String,String> pillMap = new HashMap<>(16);
public static void main(String[] args) throws Exception {
readExcel("C:\\Users\\user\\Desktop\\pill.xls",0);
writeExcel("C:\\Users\\user\\Desktop\\POS.xls",0);
}