安卓导出Excel,txt文件工具类

开始

安卓开发中,有时候会遇到到处文件的需求,尤其是平板上的开发,这个需求更为普遍,本文记录导出excel,txt文件的方法,并提供工具类,抛砖引玉,让大家遇到类似需求的时候,处理起来更为顺手。
导出工具类。使用方法

思路

导出txt文件需求比较普遍。直接进行文件读写即可。导出excel文件往往需要借助第三方jar包的帮助完成。(下载链接后续补上)

实现

需求中,往往遇到的情况是将一个列表的数据进行导出。因此本文处理的也是这种情况,直接传入列表即可。

工具类调用方法:

  ExportUtil.writeExcel(DataExportActivity.this, actionLogModels, "excel");

本文以行为日志的记录为例,具体bean类型如下:

    public static class ActionLogModel {
        private int id;
        private String action_date;
        private String action_time;
        private String user_name;
        private String user_action;
		// ... 省略 构造函数
   		// ... 省略 get set 方法
    }

文件导出工具类

/**
 * 导出工具类
 */
public class ExportUtil {
    // 内存地址
    public static String root = Environment.getExternalStorageDirectory().getPath();
    public static String saveDir =root+"/export";

    public static void writeExcel(Context context, List<ActionLogModel> actionLogModels, String fileName) throws Exception {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) && getAvailableStorage() > 1000000) {
            ToastUtil.showShort("SD卡不可用");
            return;
        }
        File file;
        File dir = new File(saveDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        file = new File(dir, fileName + ".xls");
        String[] title = {"日志id", "日期", "时间", "用户", "操作"};
        // 创建Excel工作表
        WritableWorkbook wwb;
        OutputStream os = new FileOutputStream(file);
        wwb = Workbook.createWorkbook(os);
        // 添加第一个工作表并设置第一个Sheet的名字
        WritableSheet sheet = wwb.createSheet("用户操作", 0);
        Label label;
        for (int i = 0; i < title.length; i++) {
            // Label(x,y,z) 代表单元格的第x+1列,第y+1行, 内容z
            // 在Label对象的子对象中指明单元格的位置和内容
            label = new Label(i, 0, title[i], getHeader());
            // 将定义好的单元格添加到工作表中
            sheet.addCell(label);
        }

        for (int i = 0; i < actionLogModels.size(); i++) {
            ActionLogModel actionLogModel = actionLogModels.get(i);

            Label id = new Label(0, i + 1, "" + actionLogModel.getId());
            Label date = new Label(1, i + 1, actionLogModel.getAction_date());
            Label time = new Label(2, i + 1, actionLogModel.getAction_time());
            Label user_name = new Label(3, i + 1, actionLogModel.getUser_name());
            Label user_action = new Label(4, i + 1, actionLogModel.getUser_action());

            sheet.addCell(id);
            sheet.addCell(date);
            sheet.addCell(time);
            sheet.addCell(user_name);
            sheet.addCell(user_action);
        }
        // 写入数据
        wwb.write();
        // 关闭文件
        wwb.close();
        ToastUtil.showShort("写入成功");
        if (file.exists()) {
            LogUtil.e("文件确实创建了" + file.getAbsolutePath());
        } else {
            LogUtil.e("假的,文件就没有创建" + file.getAbsolutePath());
        }
    }

    public static WritableCellFormat getHeader() {
        WritableFont font = new WritableFont(WritableFont.TIMES, 10, WritableFont.BOLD);// 定义字体
        try {
            font.setColour(Colour.BLUE);// 蓝色字体
        } catch (WriteException e1) {
            e1.printStackTrace();
        }
        WritableCellFormat format = new WritableCellFormat(font);
        try {
            format.setAlignment(jxl.format.Alignment.CENTRE);// 左右居中
            format.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);// 上下居中
            // format.setBorder(Border.ALL, BorderLineStyle.THIN,
            // Colour.BLACK);// 黑色边框
            // format.setBackground(Colour.YELLOW);// 黄色背景
        } catch (WriteException e) {
            e.printStackTrace();
        }
        return format;
    }

    /**
     * 获取SD可用容量
     */
    private static long getAvailableStorage() {
        StatFs statFs = new StatFs(root);
        long blockSize = statFs.getBlockSize();
        long availableBlocks = statFs.getAvailableBlocks();
        long availableSize = blockSize * availableBlocks;
        // Formatter.formatFileSize(context, availableSize);
        return availableSize;
    }

    //写入文件保存在根目录下面
    public static void writeTxtFile(Context context, List<ActionLogModel> list, String file_name) {
        File dir = new File(saveDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file;
//        String filename = Environment.getExternalStorageDirectory() + "/" + file_name + ".txt";
        FileOutputStream outputStream;
        try {
            file = new File(dir, file_name + ".txt");
            outputStream = new FileOutputStream(file);
//            outputStream = openFileOutput(filename, MODE_PRIVATE);
            outputStream.write("日志id\t日期\t\t时间\t用户\t操作\r\n".getBytes("utf-8"));
            for (ActionLogModel actionLogModel : list) {
                outputStream.write((actionLogModel.getId() + "\t" + actionLogModel.getAction_date() + "\t" + actionLogModel.getAction_time() + "\t"
                        + actionLogModel.getUser_name() + "\t" + actionLogModel.getUser_action() + "\r\n").getBytes("utf-8"));
            }

            LogUtil.e("path " + file.getAbsolutePath());
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.e("异常异常 ");
        }
    }
}
发布了70 篇原创文章 · 获赞 176 · 访问量 31万+

猜你喜欢

转载自blog.csdn.net/zheng_weichao/article/details/90756226