Android使用jxl快速生成Excel文件

这篇博客介绍了如何在Android应用中使用jxl库将Bean对象的数据导出为Excel表格。首先,通过build.gradle引入jxl库,然后动态申请读写外部存储权限。接着,创建User类并定义获取Excel信息的方法。设置标题格式后,创建Workbook和Sheet,并填充数据。最后,写入文件并显示成功提示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近开发的时候碰到一个需求需要bean里的数据输出成Excel表格方便用户进行统计,本人也是看了一些网上的jxl的文章边学习边总结边记录,如果有不正确的地方欢迎指出。

1.引入库

代码如下(示例):
找到你的bulid.gradle(:app)

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

2.申请权限

这里是我在优快云复制的一段动态申请。

private void requestMyPermissions() {

        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //没有授权,编写申请权限代码
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
        } else {
            Log.d("TAG", "requestMyPermissions: 有写SD权限");
        }
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //没有授权,编写申请权限代码
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 100);
        } else {
            Log.d("TAG", "requestMyPermissions: 有读SD权限");
        }
    }

Mainfest

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

如果你的file.mkdirs()返回false
可以在manifest文件中的标签下加上这个属性:

android:requestLegacyExternalStorage="true"

3.代码

先来进行一些准备工作,先准备一个User类。

public class User {
private String username;
private String userphone;
private Date userbirthday;

    public User(String username, String userphone, Date userbirthday) {
        this.username = username;
        this.userphone = userphone;
        this.userbirthday = userbirthday;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getUserphone() {
        return userphone;
    }

    public void setUserphone(String userphone) {
        this.userphone = userphone;
    }

    public Date getUserbirthday() {
        return userbirthday;
    }

    public void setUserbirthday(Date userbirthday) {
        this.userbirthday = userbirthday;
    }
    public String getExcelInfo(int j){  //这里是方便后面直接获取信息
        DateFormat dateTimeformat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String date=dateTimeformat.format(getUserbirthday());
        if(j==0)
       return getUsername();
        if(j==1)
            return getUserphone();
        if(j==2)
            return date;
        return "";
    }
}

设置标题格式的setHeader()方法

public static WritableCellFormat setHeader() {
        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();// 背景
        } catch (WriteException e) {
            e.printStackTrace();
        }
        return format;
    }

好了到这里准备工作基本已经做完了我们来看MainActivity

public class MainActivity extends AppCompatActivity {
private Button mButton;
private List<User> mUserList; //你的List
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE" };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        requestMyPermissions(); //申请权限
        mButton=findViewById(R.id.create);  
        mUserList=new LinkedList<>();
        mUserList.add(new User("张三","110",new Date()));//这里随便加几个User
        mUserList.add(new User("李四","120",new Date()));//这里随便加几个User
        mUserList.add(new User("王五","130",new Date()));//这里随便加几个User
        mUserList.add(new User("林一","140",new Date()));//这里随便加几个User
      File file=  getExternalFilesDir(null);  //安卓11文件目录获取方法
String andriod11filepath=file.getAbsolutePath();  //安卓11文件目录地址 /storage/emulated/0/Android/data/com.yang.exceldemo/files

        //        String filePath = Environment.getExternalStorageDirectory().toString() +"/Android/data/com.yang.exceldemo/Excel";   //文件保存目录
        String excelFileName = "/统计表.xls";  // 文件保存名字
        String[] title = {"姓名", "电话", "生日"}; //表格第一行的标题
        String SheetName="统计"; //表名字
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
createExcel(andriod11filepath,excelFileName,title,SheetName);
            }
        });
    }
    private void requestMyPermissions() {

        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //没有授权,编写申请权限代码
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
        } else {
            Log.d("TAG", "requestMyPermissions: 有写SD权限");
        }
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //没有授权,编写申请权限代码
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 100);
        } else {
            Log.d("TAG", "requestMyPermissions: 有读SD权限");
        }
    }

    /**
     * 生成Excel方法
     * @param filePath 生成的目录   /storage/emulated/0/Android/data/com.yang.exceldemo/files
     * @param excelFileName 文件名称 /统计表.xls
     * @param title 标题 
     * @param SheetName 当前表名
     */
    private void createExcel(String filePath,String excelFileName,String[] title,String SheetName) {
        File file = new File(filePath);
        if (!file.exists()) {
         file.mkdirs();
        }
        WritableWorkbook wwb;
        OutputStream os = null;
        try {
            os = new FileOutputStream(file.getAbsoluteFile()+excelFileName);
            wwb = Workbook.createWorkbook(os);
            WritableSheet sheet = wwb.createSheet(SheetName, 0);  //建立表
            Label label;
            //下面的headerFormat是格式可要可不要
            WritableCellFormat headerFormat = new WritableCellFormat();
            headerFormat.setAlignment(Alignment.CENTRE);//字体居中
            headerFormat.setBorder(Border.ALL, BorderLineStyle.THIN,
                    Colour.BLACK);// 黑色边框

            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], setHeader());  //setHeader可以不要 只是格式
                // 将定义好的单元格添加到工作表中
                sheet.addCell(label);
            }

            for (int i = 0; i < mUserList.size(); i++) {//双重循环添加单元格内容
                for (int j=0; j<title.length;j++){// Label(x,y,z) 代表单元格的第x+1列,第y+1行, 内容z
                    sheet.addCell(new Label(j,i+1,mUserList.get(i).getExcelInfo(j),headerFormat));//getExcelInfo(j) 按照顺序获取信息填入单元格。
                    if (mUserList.get(i).getExcelInfo(j).length() <= 4) {
                        //设置列宽
                        sheet.setColumnView(j, mUserList.get(i).getExcelInfo(j).length()  +8);
                    } else {
                        //设置列宽
                        sheet.setColumnView(j,mUserList.get(i).getExcelInfo(j).length() +5);
                    }
                }
            }
            wwb.write();
            wwb.close();
            Toast.makeText(this, "写入成功", Toast.LENGTH_LONG).show();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (RowsExceededException e) {
            e.printStackTrace();
        } catch (WriteException e) {
            e.printStackTrace();
        }

    }

    public static WritableCellFormat setHeader() {
        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();// 背景
        } catch (WriteException e) {
            e.printStackTrace();
        }
        return format;
    }

}

下面来看看结果

展示图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值