![631de30d848a113428fa5de5ab00cd00.png](https://i-blog.csdnimg.cn/blog_migrate/74f0a0f36ee8413963442f5bad35f7f8.jpeg)
需求描述
将应用内的数据导出为excel表格。
实现
添加依赖包
在app的build.gradle里面添加依赖包:
implementation group: 'net.sourceforge.jexcelapi', name: 'jxl', version: '2.6.12'
有很多读者提到该依赖有问题,笔者推测是网络代理的问题,遇到这种问题大家可以到下载对应的jar包手动导入即可:
![05f43377b8ee90b8046670c5733db0f0.png](https://i-blog.csdnimg.cn/blog_migrate/e1606b5250ac64d289ffdcb71081e9e9.jpeg)
如果还是不能成功笔者已经写好了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("账单