android2.1利用jxl来读写excel,好像有bug,高版本没有,需要时间跟踪,这里贴一个例子,使用apachi POI实现的:
java file:
package com.as400samplecode;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
public class AndroidReadExcelActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
View writeButton = findViewById(R.id.write);
writeButton.setOnClickListener(this);
View readButton = findViewById(R.id.read);
readButton.setOnClickListener(this);
View writeExcelButton = findViewById(R.id.writeExcel);
writeExcelButton.setOnClickListener(this);
View readExcelButton = findViewById(R.id.readExcel);
readExcelButton.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.write:
saveFile(this, "myFile.txt");
break;
case R.id.read:
readFile(this, "myFile.txt");
break;
case R.id.writeExcel:
saveExcelFile(this, "myExcel.xls");
break;
case R.id.readExcel:
readExcelFile(this, "myExcel.xls");
break;
}
}
private static boolean saveFile(Context context, String filename) {
// check if available and not read only
if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
Log.w("FileUtils", "Storage not available or read only");
return false;
}
// Create a path where we will place our List of objects on external
// storage
// JiuJin.hong 2012/0104
File file = new File(Environment.getExternalStorageDirectory(), filename);
PrintStream p = null; // declare a print stream object
boolean success = false;
try {
OutputStream os = new FileOutputStream(file);
// Connect print stream to the output stream
p = new PrintStream(os);
p.println("This is a TEST");
Log.w("FileUtils", "Writing file" + file);
success = true;
} catch (IOException e) {
Log.w("FileUtils", "Error writing " + file, e);
} catch (Exception e) {
Log.w("FileUtils", "Failed to save file", e);
} finally {
try {
if (null != p)
p.close();
} catch (Exception ex) {
}
}
return success;
}
private static void readFile(Context context, String filename) {
if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
Log.w("FileUtils", "Storage not available or read only");
return;
}
FileInputStream fis = null;
try {
File file = new File(context.getFilesDir(), filename);
fis = new FileInputStream(file);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
Log.w("FileUtils", "File data: " + strLine);
Toast.makeText(context, "File Data: " + strLine, Toast.LENGTH_SHORT).show();
}
in.close();
} catch (Exception ex) {
Log.e("FileUtils", "failed to load file", ex);
} finally {
try {
if (null != fis)
fis.close();
} catch (IOException ex) {
}
}
return;
}
private static boolean saveExcelFile(Context context, String filename) {
// check if available and not read only
if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
Log.w("FileUtils", "Storage not available or read only");
return false;
}
boolean success = false;
// New Workbook
Workbook wb = new HSSFWorkbook();
Cell c = null;
// Cell style for header row
CellStyle cs = wb.createCellStyle();
cs.setFillForegroundColor(HSSFColor.LIME.index);
cs.setFillPattern(CellStyle.SOLID_FOREGROUND);
// New Sheet
Sheet sheet1 = null;
sheet1 = wb.createSheet("myOrder");
// Generate column headings
Row row = sheet1.createRow(0);
c = row.createCell(0);
c.setCellValue("Item Number");
c.setCellStyle(cs);
c = row.createCell(1);
c.setCellValue("Quantity");
c.setCellStyle(cs);
c = row.createCell(2);
c.setCellValue("Price");
c.setCellStyle(cs);
sheet1.setColumnWidth(0, (15 * 500));
sheet1.setColumnWidth(1, (15 * 500));
sheet1.setColumnWidth(2, (15 * 500));
// Create a path where we will place our List of objects on external
// storage
// JiuJin.hong 2012/0104
File file = new File(Environment.getExternalStorageDirectory(), filename);
FileOutputStream os = null;
try {
os = new FileOutputStream(file);
wb.write(os);
Log.w("FileUtils", "Writing file" + file);
success = true;
} catch (IOException e) {
Log.w("FileUtils", "Error writing " + file, e);
} catch (Exception e) {
Log.w("FileUtils", "Failed to save file", e);
} finally {
try {
if (null != os)
os.close();
} catch (Exception ex) {
}
}
return success;
}
private static void readExcelFile(Context context, String filename) {
if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
Log.w("FileUtils", "Storage not available or read only");
return;
}
try {
// Creating Input Stream
File file = new File(context.getFilesDir(), filename);
FileInputStream myInput = new FileInputStream(file);
// Create a POIFSFileSystem object
POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
// Create a workbook using the File System
HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
// Get the first sheet from workbook
HSSFSheet mySheet = myWorkBook.getSheetAt(0);
/** We now need something to iterate through the cells. **/
Iterator<Row> rowIter = mySheet.rowIterator();
while (rowIter.hasNext()) {
HSSFRow myRow = (HSSFRow) rowIter.next();
Iterator<Cell> cellIter = myRow.cellIterator();
while (cellIter.hasNext()) {
HSSFCell myCell = (HSSFCell) cellIter.next();
Log.w("FileUtils", "Cell Value: " + myCell.toString());
Toast.makeText(context, "cell Value: " + myCell.toString(), Toast.LENGTH_SHORT)
.show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return;
}
public static boolean isExternalStorageReadOnly() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
return true;
}
return false;
}
public static boolean isExternalStorageAvailable() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
return true;
}
return false;
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/write"
android:text="Write Text File"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:layout_width="200dp"></Button>
<Button
android:id="@+id/read"
android:text="Read Text File"
android:layout_height="wrap_content"
android:layout_width="200dp"></Button>
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout2"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/writeExcel"
android:text="Write Excel File"
android:layout_height="wrap_content"
android:layout_width="200dp"></Button>
<Button
android:id="@+id/readExcel"
android:text="Read Excel File"
android:layout_height="wrap_content"
android:layout_width="200dp"></Button>
</LinearLayout>
</LinearLayout>
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.as400samplecode"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk
android:minSdkVersion="7" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:icon="@drawable/icon"
android:label="@string/app_name">
<activity
android:name=".AndroidReadExcelActivity"
android:label="@string/app_name">
<intent-filter>
<action
android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
poi-3.7-20101029.jar从网上下载,地址为:http://as400samplecode.blogspot.com/2011/10/android-read-write-excel-file-using.html,可以利用www.7daili.com访问下载.
adb logcat :
W/FileUtils( 365): Writing file/sdcard/myFile.txt
W/FileUtils( 365): Writing file/sdcard/myExcel.xls
D/dalvikvm( 365): GC freed 8684 objects / 492160 bytes in 66ms
I/global ( 365): Default buffer size used in BufferedReader constructor. It would be better to be explicit if an 8k-char buffer is required.
W/FileUtils( 365): File data: This is a TEST
I/NotificationService( 52): enqueueToast pkg=com.as400samplecode callback=android.app.ITransientNotification$Stub$Proxy@44de64e8 duration=0
W/FileUtils( 365): Cell Value: Item Number
I/NotificationService( 52): enqueueToast pkg=com.as400samplecode callback=android.app.ITransientNotification$Stub$Proxy@44c67430 duration=0
W/FileUtils( 365): Cell Value: Quantity
I/NotificationService( 52): enqueueToast pkg=com.as400samplecode callback=android.app.ITransientNotification$Stub$Proxy@44de6f78 duration=0
W/FileUtils( 365): Cell Value: Price
I/NotificationService( 52): enqueueToast pkg=com.as400samplecode callback=android.app.ITransientNotification$Stub$Proxy@44c65d80 duration=0