android JXL 导出Excel(.xls/xlsx)
前面使用过 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();