java读写Excel文件方法

    技术2022-05-20  46

     

    使用第三方包:jxl.jar的。

     

    public class ExcelTools {

     /**   * 写Excel   *   * @param fileName   *            输出的Excel的文件名   * @param sheetName   *            Excel工作表的名字   * @param title   *            Excel工作表中每一列的标题   * @param list   *            存入表格的内容,每一条记录为一个String[],数组中的元素与title相对应   */  public static void writeExcel(String fileName, String sheetName,    String[] title, List<String[]> list) {   WritableWorkbook workbook;   try {    OutputStream os = new FileOutputStream(fileName);    workbook = Workbook.createWorkbook(os);    WritableSheet sheet = workbook.createSheet(sheetName, 0); // 添加第一个工作表    jxl.write.Label label;    // 添加每列的标题    for (int i = 0; i < title.length; i++) {     // Label(列号,行号 ,内容 )excel坐标原点是(0,0)     label = new jxl.write.Label(i, 0, title[i]);     sheet.addCell(label);    }    if (list != null) {     for (int i = 0; i < list.size(); i++) {      String[] tt = list.get(i);      for (int z = 0; z < tt.length; z++) {       // Label(列号,行号 ,内容 )excel坐标原点是(0,0)       label = new jxl.write.Label(z, i + 1, tt[z]);       sheet.addCell(label);      }     }    }    workbook.write();    workbook.close();    os.close();   } catch (Exception e) {    e.printStackTrace();   }  }

     /**   * 读Excel   *   * @param fileName   *            文件名   * @param sheetNum   *            工作表的下标   * @return List<String[]> 集合中的一个元素为Excel表格中的一条记录   */  public static List<String[]> readExcel(String fileName, int sheetNum) {   File file = new File(fileName);   InputStream is = null;   Workbook rwb = null;   Sheet stFile = null;   List<String[]> list = new ArrayList<String[]>();   if (file.exists() && file.length() > 0) {    try {     is = new FileInputStream(file);     rwb = Workbook.getWorkbook(is);     stFile = rwb.getSheet(sheetNum);     int cols = stFile.getColumns();     for (int r = 0; r < stFile.getRows(); r++) {      String[] record = new String[cols];      for (int c = 0; c < cols; c++) {       record[c] = stFile.getCell(c, r).getContents().trim();      }      list.add(record);     }    } catch (BiffException ex) {     ex.printStackTrace();    } catch (IOException ex) {     ex.printStackTrace();    } finally {     rwb.close();     if (is != null) {      try {       is.close();      } catch (IOException e) {       e.printStackTrace();      }     }    }   }   return list;  } }


    最新回复(0)