最近使用poi从onenet导出设备信息,发现报这个异常,网上找到是都是不是Excel格式文件,另存为的问题,但是我的是poi生成的这就尴尬了
问题出在 FileOutputStream 和FileInputStream 创建位置不同
/**
* 从onenote生成excel文件
* @param jarray 数据
* @param path 文件路径
* @param currentPage 当前页
* @param perPage 每页显示数目
*/
public static void exportDeviceExcel(JSONArray jarray, String path, int currentPage , int perPage){
try{
HSSFWorkbook workbook = null;
HSSFSheet sheet = null;
FileInputStream fis = null;
//FileOutputStream fos = new FileOutputStream(new File(path)); //(1)
if(currentPage == 1){ //需要创建文件
//1.创建工作簿
workbook = new HSSFWorkbook();
//2.创建工作表
sheet = workbook.createSheet("device");
//3.1、创建头标题行; 并且设置头标题
HSSFRow row = sheet.createRow(0);
String[] titles = {"id", "private","title", "tags","location","protocol","auth_info","create_time","online"};
for(int i=0; i < titles.length; i++){
HSSFCell cell2 = row.createCell(i);
cell2.setCellValue(titles[i]);
}
}else{
fis = new FileInputStream(path);
workbook = new HSSFWorkbook(fis);
sheet = workbook.getSheet("device");
}
//4、操作单元格;将用户列表写入excel
if(jarray != null && jarray.size()>0) {
for(int j = 0; j < jarray.size(); j++){
JSONObject json = (JSONObject) jarray.get(j);
HSSFRow rowContent = sheet.createRow(j + 1 + (currentPage-1) * perPage);
HSSFCell idCell = rowContent.createCell(0);
idCell.setCellValue(json.getString("id"));
HSSFCell privateCell = rowContent.createCell(1);
privateCell.setCellValue(json.getString("private"));
HSSFCell titleCell = rowContent.createCell(2);
titleCell.setCellValue(json.getString("title"));
HSSFCell tagsCell = rowContent.createCell(3);
tagsCell.setCellValue(json.getString("tags"));
HSSFCell locationCell = rowContent.createCell(4);
locationCell.setCellValue(json.getString("location"));
HSSFCell protocolCell = rowContent.createCell(5);
protocolCell.setCellValue(json.getString("protocol"));
HSSFCell authCell = rowContent.createCell(6);
authCell.setCellValue(json.getString("auth_info"));
HSSFCell timeCell = rowContent.createCell(7);
timeCell.setCellValue(DateUtil.date2Str(json.getDate("create_time"),"yyyy-MM-dd HH:mm:ss"));
HSSFCell onlineCell = rowContent.createCell(8);
onlineCell.setCellValue(json.getBooleanValue("online")? "在线" : "离线");
}
}
FileOutputStream fos = new FileOutputStream(new File(path));
//5、输出
workbook.write(fos);
fos.close();
workbook.close();
}catch(Exception e){
e.printStackTrace();
}
}
刚才开始将FileOutputStream fos = new FileOutputStream(new File(path)); 放置在最前面(1)位置,就抛出这个异常,它不能放置这个之前 fis = new FileInputStream(path); 也就是不能先创建当前文件的输出流,读取之前保证没有其他流占用该文件。
这个方法作用:第一次查询时候需要创建表,后面的查询数据就直接追加即可。