Android将数据导出为excel文件的方法

需求描述

将应用内的数据导出为excel表格。

实现

添加依赖包

在app的build.gradle里面添加依赖包:

implementation group: 'net.sourceforge.jexcelapi', name: 'jxl', version: '2.6.12'

有很多读者提到该依赖有问题,笔者推测是网络代理的问题,遇到这种问题大家可以到这个地址下载对应的jar包手动导入即可:

屏幕快照 2019-02-14 18.44.42

如果还是不能成功笔者已经写好了jar包放在了这个地址,大家可以自由下载,下载到jar包之后将其放在app/libs目录下,然后右键jar包文件,然后Add as Library即可。

编写excel工具类

package cn.xiaojii.cashgift.util.io;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.format.Colour;
import jxl.write.Label;
import jxl.write.WritableCell;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

/**
 * @author dmrfcoder
 * @date 2018/8/9
 */
public class ExcelUtil {
    private static WritableFont arial14font = null;

    private static WritableCellFormat arial14format = null;
    private static WritableFont arial10font = null;
    private static WritableCellFormat arial10format = null;
    private static WritableFont arial12font = null;
    private static WritableCellFormat arial12format = null;
    private final static String UTF8_ENCODING = "UTF-8";
   
   /**
     * 单元格的格式设置 字体大小 颜色 对齐方式、背景颜色等...
     */
    private static void format() {
        try {
            arial14font = new WritableFont(WritableFont.ARIAL, 14, WritableFont.BOLD);
            arial14font.setColour(jxl.format.Colour.LIGHT_BLUE);
            arial14format = new WritableCellFormat(arial14font);
            arial14format.setAlignment(jxl.format.Alignment.CENTRE);
            arial14format.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
            arial14format.setBackground(jxl.format.Colour.VERY_LIGHT_YELLOW);

            arial10font = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD);
            arial10format = new WritableCellFormat(arial10font);
            arial10format.setAlignment(jxl.format.Alignment.CENTRE);
            arial10format.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
            arial10format.setBackground(Colour.GRAY_25);

            arial12font = new WritableFont(WritableFont.ARIAL, 10);
            arial12format = new WritableCellFormat(arial12font);
            //对齐格式
            arial10format.setAlignment(jxl.format.Alignment.CENTRE);
            //设置边框
            arial12format.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);

        } catch (WriteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化Excel
     *
     * @param fileName 导出excel存放的地址(目录)
     * @param colName excel中包含的列名(可以有多个)
     */
    public static void initExcel(String fileName, String[] colName) {
        format();
        WritableWorkbook workbook = null;
        try {
            File file = new File(fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
            workbook = Workbook.createWorkbook(file);
           //设置表格的名字
            WritableSheet sheet = workbook.createSheet("账单", 0);
            //创建标题栏
            sheet.addCell((WritableCell) new Label(0, 0, fileName, arial14format));
            for (int col = 0; col < colName.length; col  ) {
                sheet.addCell(new Label(col, 0, colName[col], arial10format));
            }
            //设置行高
            sheet.setRowView(0, 340);
            workbook.write();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> void writeObjListToExcel(List<T> objList, String fileName, Context c) {
     if (objList != null && objList.size() > 0) {
            WritableWorkbook writebook = null;
            InputStream in = null;
            try {
                WorkbookSettings setEncode = new WorkbookSettings();
                setEncode.setEncoding(UTF8_ENCODING);
                in = new FileInputStream(new File(fileName));
                Workbook workbook = Workbook.getWorkbook(in);
                writebook = Workbook.createWorkbook(new File(fileName), workbook);
                WritableSheet sheet = writebook.getSheet(0);

                for (int j = 0; j < objList.size(); j  ) {
                    ProjectBean projectBean = (ProjectBean) objList.get(j);
                    List<String> list = new ArrayList<>();
                    list.add(projectBean.getName());
                    list.add(projectBean.getProject());
                    list.add(projectBean.getMoney());
                    list.add(projectBean.getYear()   " "   projectBean.getMonth() " " projectBean.getDay());
                    list.add(projectBean.getBeizhu());

                    for (int i = 0; i < list.size(); i  ) {
                        sheet.addCell(new Label(i, j   1, list.get(i), arial12format));
                        if (list.get(i).length() <= 4) {
                            //设置列宽
                            sheet.setColumnView(i, list.get(i).length()   8);
                        } else {
                            //设置列宽
                            sheet.setColumnView(i, list.get(i).length()   5);
                        }
                    }
                    //设置行高
                    sheet.setRowView(j   1, 350);
                }

                writebook.write();
                Toast.makeText(c, "导出Excel成功", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (writebook != null) {
                    try {
                        writebook.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }
}

使用


		String filePath = Environment.getExternalStorageDirectory()   "/AndroidExcelDemo";
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();
        }


        String excelFileName = "/demo.xls";


        String[] title = {"姓名", "年龄", "男孩"};
        String sheetName = "demoSheetName";


        List<DemoBean> demoBeanList = new ArrayList<>();
        DemoBean demoBean1 = new DemoBean("张三", 10, true);
        DemoBean demoBean2 = new DemoBean("小红", 12, false);
        DemoBean demoBean3 = new DemoBean("李四", 18, true);
        DemoBean demoBean4 = new DemoBean("王香", 13, false);
        demoBeanList.add(demoBean1);
        demoBeanList.add(demoBean2);
        demoBeanList.add(demoBean3);
        demoBeanList.add(demoBean4);
        filePath = filePath   excelFileName;


        ExcelUtil.initExcel(filePath, sheetName, title);


        ExcelUtil.writeObjListToExcel(demoBeanList, filePath, context);

        textView.setText("excel已导出至:"   filePath);

最终生成的excel效果如下:
image-20190216174313758

注意,一定要申请读写文件的权限,不然会导出失败,完整demo在github

  • 22
    点赞
  • 153
    收藏
    觉得还不错? 一键收藏
  • 61
    评论
要使用Java的EasyExcel库将数据导出Excel文件,需要进行以下步骤: 1. 在Java项目中添加EasyExcel库的依赖。 2. 创建一个实体类,用于表示Excel文件中的一行数据。该实体类的成员变量应该与Excel文件中的列对应。 3. 在Java代码中,使用EasyExcel提供的API将数据写入Excel文件。可以使用EasyExcel提供的Writer对象将数据写入文件,或者使用EasyExcel提供的注解将数据直接写入文件。 4. 在Uniapp中,使用uni.request()方法向Java后端发送请求,获取生成Excel文件。 下面是一个示例代码,用于将数据导出Excel文件: Java代码: ```java public class ExportExcel { public static void main(String[] args) throws IOException { // 创建一个写Excel的对象 String fileName = "test.xlsx"; OutputStream out = new FileOutputStream(fileName); ExcelWriter writer = EasyExcel.write(out).build(); // 写数据Excel文件中 List<DemoData> data = getData(); WriteSheet sheet = EasyExcel.writerSheet("sheet1").build(); writer.write(data, sheet); // 关闭Excel写对象和输出 writer.finish(); out.close(); } private static List<DemoData> getData() { List<DemoData> data = new ArrayList<>(); for (int i = 0; i < 10; i++) { DemoData item = new DemoData(); item.setName("Name " + i); item.setAge(i); item.setEmail("email" + i + "@example.com"); data.add(item); } return data; } } @Data public class DemoData { @ExcelProperty("姓名") private String name; @ExcelProperty("年龄") private int age; @ExcelProperty("邮箱") private String email; } ``` Uniapp代码: ```javascript uni.request({ url: 'http://localhost:8080/exportExcel', responseType: 'arraybuffer', success: (res) => { let fileName = 'test.xlsx'; let filePath = plus.android.invoke("Environment", "getExternalStorageDirectory") + '/' + fileName; plus.io.resolveLocalFileSystemURL(filePath, function(entry) { entry.createWriter(function(writer) { writer.onwrite = function() { console.log('write success'); }; writer.write(new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })); }); }); } }); ``` 在这个示例代码中,Java后端在8080端口上提供了一个名为/exportExcel的接口,用于导出Excel文件。Uniapp前端使用uni.request()方法向这个接口发送请求,并将响应数据保存为Excel文件

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 61
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值