前面使用過 POI 導出xlsx但是它體量比較大,功能較豐富,在一些對包size比較敏感并且導出需求相對簡單的項目中就不太適合。
poi鏈接:Android 導入導出excel xls、xlsx_android excel導入導出-CSDN博客
jxl 包體積小,使用簡單、API 直觀。
1.導入依賴
implementation("net.sourceforge.jexcelapi:jxl:2.6.12")
2.導出方式,可根據自身需求修改
public static boolean exportExcel(Context context, List<Contact> contactList) {try {File dir = context.getExternalFilesDir(null);File file = new File(dir, "聯系人.xlsx");if (file.exists()) {file.delete();}WritableWorkbook workbook = Workbook.createWorkbook(file);WritableSheet sheet = workbook.createSheet("聯系人", 0);// 設置列寬(單位:字符數) 可根據實際情況調整sheet.setColumnView(0, 10); // 姓名sheet.setColumnView(1, 20); // 組織sheet.setColumnView(2, 15); // 個人電話sheet.setColumnView(3, 15); // 家庭電話sheet.setColumnView(4, 15); // 工作電話sheet.setColumnView(5, 30); // 郵箱sheet.setColumnView(6, 40); // 備注// 寫入表頭sheet.addCell(new Label(0, 0, "姓名"));sheet.addCell(new Label(1, 0, "組織"));sheet.addCell(new Label(2, 0, "個人電話"));sheet.addCell(new Label(3, 0, "家庭電話"));sheet.addCell(new Label(4, 0, "工作電話"));sheet.addCell(new Label(5, 0, "郵箱"));sheet.addCell(new Label(6, 0, "備注"));// 寫入數據for (int i = 0; i < contactList.size(); i++) {Contact c = contactList.get(i);sheet.addCell(new Label(0, i + 1, c.getName()));sheet.addCell(new Label(1, i + 1, c.getOrg()));sheet.addCell(new Label(2, i + 1, c.getPhone()));sheet.addCell(new Label(3, i + 1, c.getHomePhone()));sheet.addCell(new Label(4, i + 1, c.getWorkPhone()));sheet.addCell(new Label(5, i + 1, c.getEmail()));sheet.addCell(new Label(6, i + 1, c.getNote()));}workbook.write();workbook.close();Log.d("導出文件", "導出成功 path:" + file.getPath());return true;} catch (Exception e) {e.printStackTrace();}return false;}public static class Contact {private String Name;private String phone;private String email;private String org;private String note;private String homePhone;private String workPhone;get set 省略}
3.使用
new Thread(new Runnable() {@Overridepublic void run() {List<ExportFile.Contact> contacts = new ArrayList<>();for (int i = 0; i < 10; i++) {ExportFile.Contact contact = new ExportFile.Contact();contact.setName("劉二毛" + i);contact.setPhone("1234567890" + i);contact.setHomePhone("0395-550999" + i);contact.setWorkPhone("0397-999999" + i);contact.setEmail("liuermao666@Gmail.eslssdkj.com");contact.setNote("備注" + i);contact.setOrg("組織結構" + i);contacts.add(contact);}boolean result = ExportFile.exportExcel(ActivityLianXiRen.this, contacts);}}).start();