參考自:
https://blog.csdn.net/yangbin0513/article/details/51782525
https://blog.csdn.net/qq_36982160/article/details/82421940
https://www.jianshu.com/p/1becf5aef94a
1.添加jxl jar包
下載完成添加到libs目錄,並引入
2.添加權限(讀寫權限需要動態獲取)
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"
tools:ignore="ProtectedPermissions" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!-- 往SDCard寫入數據權限 -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
3.創建需要保存數據的javabean對象
public class Student {
private String name;
private int age;
private String sex;
private int score;
public Student(String name, int age, String sex, int score) {
this.name = name;
this.age = age;
this.sex = sex;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String boy) {
this.sex = boy;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
4.創建操作Excel的工具類
import android.content.Context;
import android.widget.Toast;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
/**
* @author Panner
* @version 2020-05-17 21:30
*/
public class SaveExcelUtil {
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 {
//字體 ARIAL, 字號 14 bold 粗體
arial14font = new WritableFont(WritableFont.ARIAL, 14, WritableFont.BOLD);
arial14font.setColour(Colour.LIGHT_BLUE);//字體的顏色
arial14font.setUnderlineStyle(UnderlineStyle.SINGLE);//設置下劃線
//初始化單元格格式
arial14format = new WritableCellFormat(arial14font);
arial14format.setAlignment(Alignment.CENTRE);//對齊方式
arial14format.setBorder(Border.ALL, BorderLineStyle.THIN);//邊框的格式
arial14format.setBackground(Colour.VERY_LIGHT_YELLOW);//底色
arial10font = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD);
arial10format = new WritableCellFormat(arial10font);
arial10format.setAlignment(Alignment.CENTRE);
arial10format.setBorder(Border.ALL, BorderLineStyle.THIN);
arial10format.setBackground(Colour.GRAY_25);
arial12font = new WritableFont(WritableFont.ARIAL, 10);
arial12format = new WritableCellFormat(arial12font);
arial12format.setAlignment(Alignment.CENTRE);
arial12format.setBorder(Border.ALL, BorderLineStyle.THIN);
} catch (WriteException e) {
e.printStackTrace();
}
}
/**
* 初始化Excel
* 寫入字段名稱,表名
*
* @param filePath 導出excel的存放地址
* @param sheetName Excel表格的表名
* @param colName excel中包含的列名
*/
public static void initExcel(File filePath, String sheetName, String[] colName) {
format();
//創建一個工作薄,就是整個Excel文檔
WritableWorkbook workbook = null;
try {
// File file = new File(filePath);
if (!filePath.exists()) {
filePath.createNewFile();
}
//使用Workbook創建一個工作薄,就是整個Excel文檔
workbook = Workbook.createWorkbook(filePath);
//設置表格的名稱(兩個參數分別是工作表名字和插入位置,這個位置從0開始)
WritableSheet sheet = workbook.createSheet(sheetName, 0);
//創建label標籤:實際就是單元格的標籤(三個參數分別是:col + 1列,row + 1行, 內容, 單元格格式)
// Label label = new Label(0, 0, filePath, arial14format);//設置第一行的單元格標籤爲:標題
//將標籤加入到工作表中
// sheet.addCell(label);
//通過writablesheet.mergeCells(int x,int y,int m,int n);來實現的。
// 表示將從第x+1列,y+1行到m+1列,n+1行合併 (四個點定義了兩個座標,左上角和右下角)
sheet.mergeCells(0, 0, colName.length - 1, 0);
sheet.addCell(new Label(0, 0, "我是標題", arial14format));
sheet.setRowView(0, 520);
//再同一個單元格中寫入數據,上一個數據會被下一個數據覆蓋
for (int col = 0; col < colName.length; col++) {
sheet.addCell(new Label(col, 1, colName[col], arial10format));
}
//設置行高 參數的意義爲(第幾行, 行高)
sheet.setRowView(1, 340);
workbook.write();// 寫入數據
} catch (IOException | WriteException e) {
e.printStackTrace();
} finally {
if (workbook != null) {
try {
workbook.close();// 關閉文件
} catch (IOException | WriteException e) {
e.printStackTrace();
}
}
}
}
/**
* 見指定類型的List寫入到Excel文件中
*
* @param objList 代寫入的List
* @param fileName
* @param context
* @param <T>
*/
public static <T> void writeObjListToExcel(List<T> objList, String fileName, Context context) {
if (objList != null && objList.size() > 0) {
//創建一個工作薄,就是整個Excel文檔
WritableWorkbook writeBook = null;
InputStream in = null;
try {
WorkbookSettings settings = new WorkbookSettings();
settings.setEncoding(UTF8_ENCODING);
in = new FileInputStream(new File(fileName));
//Workbook不但能用來創建工作薄,也可以讀取現有的工作薄
Workbook workbook = Workbook.getWorkbook(in);
//創建一個工作薄,就是整個Excel文檔
writeBook = Workbook.createWorkbook(new File(fileName), workbook);
//讀取表格
WritableSheet sheet = writeBook.getSheet(0);
for (int j = 0; j < objList.size(); j++) {
Student student = (Student) objList.get(j);
List<String> list = new ArrayList<>();
list.add(student.getName());
list.add(String.valueOf(student.getAge()));
list.add(String.valueOf(student.getSex()));
list.add(String.valueOf(student.getScore()));
for (int i = 0; i < list.size(); i++) {
sheet.addCell(new Label(i, j + 2, list.get(i), arial12format));//向一行中添加數據
if (list.get(i).length() <= 4) {
//設置列寬
sheet.setColumnView(i, list.get(i).length() + 8);
} else {
sheet.setColumnView(i, list.get(i).length() + 5);
}
}
//設置行高
sheet.setRowView(j + 1, 350);
}
writeBook.write();
workbook.close();
Toast.makeText(context, "導出Excel成功", Toast.LENGTH_SHORT).show();
} catch (IOException | BiffException | WriteException e) {
e.printStackTrace();
} finally {
if (writeBook != null) {
try {
writeBook.close();
} catch (IOException | WriteException e) {
e.printStackTrace();
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
5.activity中使用
activity_save_excel.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/export_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginTop="20dp"
android:text="導出"
tools:layout_editor_absoluteX="161dp"
tools:layout_editor_absoluteY="341dp" />
</RelativeLayout>
MainActivity.class:
public class SaveExcelActivity extends AppCompatActivity implements View.OnClickListener {
private AlertDialog alertDialog;
String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
private int REQUEST_PERMISSION_CODE = 1000;
//請求權限
private void requestPermission() {
if (Build.VERSION.SDK_INT > 23) {
if (ContextCompat.checkSelfPermission(SaveExcelActivity.this, permissions[0]) == PackageManager.PERMISSION_GRANTED) {
Log.e(getLocalClassName(),"requestPermission:" + "用戶之前已經授予了權限!");
} else {
requestPermissions(permissions, REQUEST_PERMISSION_CODE);
}
}
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_save_excel);
requestPermission();
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
builder.detectFileUriExposure();
Button exportButton = findViewById(R.id.export_button);
exportButton.setOnClickListener(this);
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSION_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.e(getLocalClassName(),"申請成功");
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(SaveExcelActivity.this);
builder.setTitle("permission");
builder.setMessage("點擊允許纔可以使用");
builder.setPositiveButton("去允許", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (alertDialog != null && alertDialog.isShowing()) {
alertDialog.dismiss();
}
ActivityCompat.requestPermissions(SaveExcelActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
});
alertDialog = builder.create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
}
}
}
private void showDialogTipUserRequestPermission() {
ActivityCompat.requestPermissions(this, permissions, 321);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.export_button:
exportExcel(this);
break;
case R.id.open_button:
openDir();
default:
break;
}
}
private void openDir() {
File file = new File(Environment.getExternalStorageState());
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setDataAndType(Uri.fromFile(file), "file/*");
try {
startActivity(intent);
} catch (Exception e) {
Toast.makeText(this, "沒用正確打開文件管理器", Toast.LENGTH_SHORT).show();
}
}
//導出
private void exportExcel(Context context) {
String path = getExternalFilesDir("exter_test").getPath();
String fileName00 = "test.txt";
File file = new File(path+"/"+"xxxxxxx");
try {
if (!file.exists()) {
boolean mkdir = file.mkdir();//創建文件夾
}
}catch (Exception e){
e.printStackTrace();
}
File files=new File(file.getPath()+"/"+"text.xls");
try {
if(!files.exists()) {
boolean newFile = files.createNewFile();//創建文件
}
} catch (IOException e) {
e.printStackTrace();
}
String[] title = {"姓名", "年齡", "男孩","分數"};
String sheetName = "表格名稱";
List<Student> demoBeanList = new ArrayList<>();
Student demoBean1 = new Student("張三", 10, "男",80);
Student demoBean2 = new Student("李四", 11, "男",90);
Student demoBean3 = new Student("王二", 12, "男",88);
Student demoBean4 = new Student("麻子", 13, "男",100);
demoBeanList.add(demoBean1);
demoBeanList.add(demoBean2);
demoBeanList.add(demoBean3);
demoBeanList.add(demoBean4);
List<List<String>> strings = new ArrayList<>();
List<String> strings1 = new ArrayList<>();
strings1.add("zhangsan");
strings1.add("10");
strings1.add("nan");
strings1.add("80");
strings.add(strings1);
SaveExcelUtil.initExcel(files, sheetName, title);
SaveExcelUtil.writeObjListToExcel(demoBeanList, files.getPath(), context);
}
@Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
}
備註:點擊導出就可以在手機內存中找到保存的Excel文件了,路徑爲:Android/data/com.xxx.yyy/files/exter_text/text.xls