jxl导入Excel文件
处理excel文件有多种方式,我晓得的架包就有jxl和poi两种。
此处我描述采用jxl实现。
导出excel文件,代码如下
public static void exportExcel(String filename, String[] datas) { WritableWorkbook workbook = null;//创建excel文件对象 try { OutputStream os = new FileOutputStream(filename);//新建文件输出对象 workbook = Workbook.createWorkbook(os); WritableSheet sheet = workbook.createSheet("taskuser", 0);//创建excel工作簿对象 Label label; for (int i = 0; i < datas.length; i++) { // Label(列号,行号 ,内容 ) label = new Label(0, i, datas[i]); // in row1 sheet.addCell(label); } workbook.write(); } catch (Exception e) { logger.error(e.toString()); } finally { if (workbook != null) { try { workbook.close(); } catch (Exception ex) { workbook = null; } } }}?
?
传递进来的参数有文件路径(带文件名)、数据(数组形式,当然也可以是list或者map等,相对应更改下面for处理方式即可)
?
代码段中没有处理格式、样式等
?
导入excel文件(传递的参数为文件路径):
public static String importExcel(String filename) throws Exception { File file = null; Workbook wb = null; String datas = ""; try { file = new File(filename); wb = Workbook.getWorkbook(file); Sheet st = wb.getSheet(0);//获取工作簿 int rows = st.getRows();//获取总行数 Cell cell = null;//循环获取值 for (int i = 0; i < rows; i++) { cell = st.getCell(0, i); datas += cell.getContents() + ","; } } finally { if (wb != null) { wb.close(); wb = null; } if (file != null) { file.delete(); file = null; } } return datas; }?最后返回值为String,且处理为带[ , ]所以可以再转换为数组或者json对象。如果要处理为list等泛型可在获取值的时候做不同的处理。
?
?
后附jxl架包一个,,,