java 操作Excel

public class WriteExcel {
private static final String EXCEL_XLS = "xls";
private static final String EXCEL_XLSX = "xlsx";



public static void main(String[] Args) throws IOException{
Map<String,String> map = new HashMap<>();

//只有第2/3/4/5列需要重新填写,其他的默认即可
map.put("m1","XXX1"+1234);
map.put("m2","XXX1"+4321);
map.put("m3","10001");
map.put("m4","0-1-11");
writeExcel(map, 4, "C:\\Users\\Administrator\\Desktop\\template .xls");
}
public static void writeExcel(Map dataList, int cloumnCount,String finalXlsxPath) throws IOException{
OutputStream out = null;
try {
// 获取总列数
// int columnNumCount = cloumnCount;
// 读取Excel文档
File finalXlsxFile = new File(finalXlsxPath);
Workbook workBook = getWorkbok(finalXlsxFile);
// sheet 对应一个工作页
Sheet sheet = workBook.getSheetAt(0);
/**
* 往Excel中写新数据
*/


// 创建一行:从第三行开始,跳过标题列、属性列
// Row row = sheet.createRow(2);
Row row = sheet.getRow(2);
// 得到要插入的每一条记录
Map map = dataList;
String[] n = new String[columnNumCount];

for (int k = 0; k <
columnNumCount; k++) {
                // 在一行内循环
String aa = "m"+(k+1);
n[k] = map.get(aa).toString();
Cell c1 = row.createCell(k+1);
c1.setCellValue(n[k]);


}

// 创建文件输出流,准备输出电子表格:这个必须有,否则你在sheet上做的任何操作都不会有效
out = new FileOutputStream(finalXlsxPath);
workBook.write(out);
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
if(out != null){
out.flush();
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("数据导出成功");
}

/**
* 判断Excel的版本,获取Workbook
* @return
* @throws IOException
*/
public static Workbook getWorkbok(File file) throws IOException{
Workbook wb = null;
FileInputStream in = new FileInputStream(file);
if(file.getName().endsWith(EXCEL_XLS)){ //Excel 2003
wb = new HSSFWorkbook(in);
}else if(file.getName().endsWith(EXCEL_XLSX)){ // Excel 2007/2010
wb = new XSSFWorkbook(in);
}
return wb;
}
}
posted @ 2017-03-14 14:01  wxjhappy  阅读(336)  评论(0编辑  收藏  举报