「这是我参与11月更文挑战的第9天,活动详情查看:2021最后一次更文挑战」
-
创建Workbook对象(工作簿): XSSFWorkbook或者HSSFWorkbook或者WorkbookFactory三种方式创建。 创建Sheet对象(excle表格中的页):
-
Workbook对象调用createSheet() ,被创建的Sheets将按顺序自动添加到工作簿中。Sheets默认是没有名字的,通过Workbook.setSheetName(sheetindex,”SheetName”,encoding)来设置。
-
创建Row对象(行):
通过Sheets对象通过createRow(rowNumber) 来创建Rows 。Row需具备单元格值才能添加到Excel表格中。 行高可以通过setRowHeight(heightVal)来设置 -
创建Cell对象(单元格):
通过Row对象调用 createCell(column, type)创建Cells(单元格)。只有具备值的Cell才能添加到Row中。 -
FileOutputStream来生成Excel表格:
调用Workbook对象调用write(outputStream),将工作簿传递给OutputStream (FileOutputStream 或 者ServletOutputStream),需自己关闭OutputStream.
作者——新根
导入依赖
implementation group: 'org.apache.poi', name: 'poi-ooxml', version: '3.17'
implementation group: 'org.apache.xmlbeans', name: 'xmlbeans', version: '3.1.0'
implementation 'javax.xml.stream:stax-api:1.0'
implementation 'com.fasterxml:aalto-xml:1.2.2'
复制代码
利用FileOutputStream导出excel到外部储存
String mSDCardFolderPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/快递数据";
File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), convertTime(System.currentTimeMillis(),"MM月dd日HH时mm分")+".xlsx");
//写上日期
File excel = new File(dir, convertTime(System.currentTimeMillis(), "MM月dd日HH时mm分") + ".xlsx");
FileOutputStream fos = new FileOutputStream(excel);
wb.write(fos);
fos.flush();
fos.close();
复制代码
完整代码
/**
* 导出Excel
* @param listData
* @return
*/
public static boolean exportExcel(List<PhonebillExpressBean> listData) {
try {
// 创建excel xlsx格式
Workbook wb = new XSSFWorkbook();
// 创建工作表
Sheet sheet = wb.createSheet();
String[] title = {"用户", "寄件人姓名", "寄件人手机号", "寄件人省/市/区", "寄件人详细地址", "收件人姓名", "收件人手机号", "收件人省/市/区", "收件人详细地址",
"实付款", "佣金", "创建时间"};
//创建行对象
Row row = sheet.createRow(0);
// 设置有效数据的行数和列数
int colNum = title.length; // {"用户", "寄件人姓名", "寄件人手机号", "寄件人省/市/区", "寄件人详细地址", "收件人姓名", "收件人手机号", "收件人省/市/区", "收件人详细地址","实付款", "佣金","创建时间"}
for (int i = 0; i < colNum; i++) {
sheet.setColumnWidth(i, 20 * 256); // 显示20个字符的宽度
Cell cell1 = row.createCell(i);
//第一行
cell1.setCellValue(title[i]);
}
// 导入数据
for (int rowNum = 0; rowNum < listData.size(); rowNum++) {
// 之所以rowNum + 1 是因为要设置第二行单元格
row = sheet.createRow(rowNum + 1);
// 设置单元格显示宽度
row.setHeightInPoints(28f);
// PhonebillExpressBean 这个是我的业务类,这个是根据业务来进行填写数据
PhonebillExpressBean bean = listData.get(rowNum);
for (int j = 0; j < title.length; j++) {
Cell cell = row.createCell(j);
//要和title[]一一对应
switch (j) {
case 0:
//用户
cell.setCellValue(bean.getUserData().getPhoneNumber());
break;
case 1:
//寄件人姓名
cell.setCellValue(bean.getSenderName());
break;
case 2:
//寄件人手机号
cell.setCellValue(bean.getSenderPhoneNumber());
break;
case 3:
//寄件人省/市/区
cell.setCellValue(bean.getSenderState());
break;
case 4:
//寄件人详细地址
cell.setCellValue(bean.getSenderDetailed());
break;
case 5:
//收件人姓名
cell.setCellValue(bean.getAddresseeName());
break;
case 6:
//收件人手机号
cell.setCellValue(bean.getAddresseePhone());
break;
case 7:
//收件人省/市/区
cell.setCellValue(bean.getAddresseeState());
break;
case 8:
//收件人详细地址
cell.setCellValue(bean.getAddresseeDetailed());
break;
case 9:
//实付款
cell.setCellValue(bean.getPrice() + "元");
break;
case 10:
//佣金
cell.setCellValue(bean.getCommission() + "元");
break;
case 11:
//创建时间
cell.setCellValue(bean.getCreatedAt());
break;
}
}
}
String mSDCardFolderPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/快递数据";
File dir = new File(mSDCardFolderPath);
//判断文件是否存在
if (!dir.isFile()) {
//不存在则创建
dir.mkdir();
}
// File excel=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), convertTime(System.currentTimeMillis(),"MM月dd日HH时mm分")+".xlsx");
File excel = new File(dir, convertTime(System.currentTimeMillis(), "MM月dd日HH时mm分") + ".xlsx");
FileOutputStream fos = new FileOutputStream(excel);
wb.write(fos);
fos.flush();
fos.close();
return true;
} catch (IOException e) {
Log.e("ExpressExcle", "exportExcel", e);
return false;
}
}
复制代码
//时间戳转换字符串
public static String convertTime(long time, String patter) {
SimpleDateFormat sdf = new SimpleDateFormat(patter);
return sdf.format(new Date(time));
}
复制代码
异步
//开启一个子线程
new Thread(new Runnable() {
@Override
public void run() {
boolean isSuccess = ExpressExcle.exportExcel(list);
//返回UI线程
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
dismissLoad();
if (isSuccess) {
Toast.makeText(getContext(), "导出成功:/storage/emulated/0/Download/", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getContext(), "导出失败", Toast.LENGTH_SHORT).show();
}
}
});
}
}).start();
复制代码
储存权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
复制代码
适配安卓Q
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="cn.xy.phonebilladmin.fileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
复制代码
res文件夹下新建一个xml文件夹
file_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<paths>
<root-path
name="root"
path="" />
<files-path
name="files"
path="" />
<cache-path
name="cache"
path="" />
<external-path
name="external"
path="" />
<external-files-path
name="external_file_path"
path="" />
<external-cache-path
name="external_cache_path"
path="" />
</paths>
</resources>
复制代码
动态申请储存权限
private static final int REQUEST_CODE = 1;
private void checkPermission() {
try {
String[] PERMISSIONS_STORAGE = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
int permission = ActivityCompat.checkSelfPermission(this, "android.permission.WRITE_EXTERNAL_STORAGE");
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_CODE);
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
}
复制代码
嘻嘻