栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Android使用jxl快速生成Excel文件

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android使用jxl快速生成Excel文件

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

1.引入库

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

implementation group: 'net.sourceforge.jexcelapi', name: 'jxl', version: '2.6.12'
2.申请权限

这里是我在CSDN复制的一段动态申请。

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


    

如果你的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 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权限");
        }
    }

    
    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// 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;
    }

}

下面来看看结果

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/943333.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号