AndroidでExcelを操作するサンプルプログラム
1.システム要件:
jxl.jarをダウンロード
権限を追加
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
2.Javaコード:
public class OperateExcelActivity extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView textView = (TextView)findViewById(R.id.tv);
String path = “mnt/sdcard/test.xls";
writeExcel(path);
textView.setText(readExcel(path,5,5)+readExcel(path,10,10));
}
public void writeExcel(String fileName)
{
WritableWorkbook wwb = null;
try
{
//書き込み可能なworkbookオブジェクトを作成
wwb = Workbook.createWorkbook(new File(fileName));
} catch (IOException e)
{
e.printStackTrace();
}
if (wwb != null)
{
// 最初のパラメータはシートの名前、第二パラメータはシートの位置
WritableSheet ws = wwb.createSheet(“sheet1", 0);
//
Label lbl1 = new Label(5, 5, “Excel");
Label bll2 = new Label(10, 10, “操作");
try
{
ws.addCell(lbl1);
ws.addCell(bll2);
} catch (RowsExceededException e1)
{
e1.printStackTrace();
} catch (WriteException e1)
{
e1.printStackTrace();
}
try
{
//メモリからファイルを書き込む
wwb.write();
wwb.close();
} catch (IOException e)
{
e.printStackTrace();
} catch (WriteException e)
{
e.printStackTrace();
}
}
}
public String readExcel(String path, int x, int y)
{
String content = “";
try
{
Workbook book = Workbook.getWorkbook(new File(path));
Sheet sheet = book.getSheet(0);
//x行y列のセルの内容を取得
String cellStr = sheet.getRow(x)[y].getContents();
content = cellStr;
} catch (BiffException e)
{
content = “";
e.printStackTrace();
} catch (IOException e)
{
content = “";
e.printStackTrace();
}
return content;
}
}