Android excel表操作
阿新 • • 發佈:2019-01-12
今天學習下Android中將資料儲存到 excel 表中,本文是在下面文獻基礎上進行的復現:
https://blog.csdn.net/linzhenxiang123/article/details/53730439
一、MainActivity 程式碼
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private EditText name = null;
private EditText sex = null;
private EditText phone = null ;
private EditText address = null;
private Button button = null;
private ExcelUtil excelUtil = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText)findViewById(R.id.name);
sex = (EditText)findViewById(R.id.sex);
phone = (EditText)findViewById(R.id.phone);
address = (EditText)findViewById(R.id.address);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this );
excelUtil = new ExcelUtil(MainActivity.this,"/sdcard/test.xls");
}
@Override
public void onClick(View v) {
String name1 = name.getText().toString();
String sex1 = sex.getText().toString();
String phone1 = phone.getText().toString();
String address1 = address.getText().toString();
excelUtil.writeToExcel(name1,sex1,phone1,address1);
}
}
二、 Excel 操作
下面是 excel 操作的主要程式碼
import android.app.Activity;
import android.widget.Toast;
import java.io.File;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class ExcelUtil {
private WritableWorkbook wwb;
private File excelFile;
private Activity activity;
public ExcelUtil(Activity activity, String excelPath) {
this.activity = activity;
excelFile = new File(excelPath);
createExcel(excelFile);
}
public void createExcel(File file) {
WritableSheet ws = null;
try {
if (!file.exists()) {
wwb = Workbook.createWorkbook(file);
ws = wwb.createSheet("sheet1", 0);
Label lbl1 = new Label(0, 0, "姓名");
Label lbl2 = new Label(1, 0, "性別");
Label lbl3 = new Label(2, 0, "電話");
Label lbl4 = new Label(3, 0, "地址");
ws.addCell(lbl1);
ws.addCell(lbl2);
ws.addCell(lbl3);
ws.addCell(lbl4);
wwb.write();
wwb.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void writeToExcel(Object... args) {
try {
Workbook oldWwb = Workbook.getWorkbook(excelFile);
wwb = Workbook.createWorkbook(excelFile, oldWwb);
WritableSheet ws = wwb.getSheet(0);
int row = ws.getRows();
Label lab1 = new Label(0, row, args[0] + "");
Label lab2 = new Label(1, row, args[1] + "");
Label lab3 = new Label(2, row, args[2] + "");
Label lab4 = new Label(3, row, args[3] + "");
ws.addCell(lab1);
ws.addCell(lab2);
ws.addCell(lab3);
ws.addCell(lab4);
wwb.write();
wwb.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
三、 jar包
CSDN 上有免積分的 jxl jar 可下載
四、問題
1.容易出現問題 bug :the input file was not found ;可以嘗試 直接在桌面上建立 xls檔案,並匯入到手機準備放置的路徑下(即不通過程式碼建立xls檔案);
2.發現將 txt 檔案按照一定的個數儲存,然後txt 可以直接匯入到 excel,感覺效果是一樣的;如果沒有非常必須的需求(感覺這個直接儲存excel問題還是太多),可以儲存先為txt (桌面上用excel 重新載入下就可以了,可以檢視 txt匯入excel)