- Add permission to menifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
2. Download jxcel.jar and under libs folder.
3. Add this file to build.gradle.
compile files('src/main/libs/jxl.jar')
4. Following is the code to make workbook and add caption to worksheet
public static void makeExcelFile() {
try {
final File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Folder" + "/");
if (!dir.exists()) {
if (!dir.mkdirs()) {
Log.e("ALERT", "could not create the directories");
}
}
myFile = new File(dir, Constants.LOGGING_EXCEL_FILE_NAME);
if (!myFile.exists()) {
myFile.createNewFile();
}
WorkbookSettings wbSettings = new WorkbookSettings();
wbSettings.setLocale(new Locale("en", "EN"));
WritableWorkbook workbook = Workbook.createWorkbook(myFile, wbSettings);
workbook.createSheet(Constants.LOGGING_EXCEL_WORK_SHEET, 0);
WritableSheet workSheet = workbook.getSheet(0);
// Lets create a times font
WritableFont times10pt = new WritableFont(WritableFont.TIMES, 10);
// Define the cell format
times = new WritableCellFormat(times10pt);
// Lets automatically wrap the cells
times.setWrap(true);
// create create a bold font with unterlines
WritableFont times10ptBoldUnderline = new WritableFont(WritableFont.TIMES, 10, WritableFont.BOLD, false,
UnderlineStyle.SINGLE);
timesBoldUnderline = new WritableCellFormat(times10ptBoldUnderline);
// Lets automatically wrap the cells
timesBoldUnderline.setWrap(true);
// Write a few headers
addCaption(workSheet, 0, 0, "cap 1");
workbook.write();
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}private void addCaption(WritableSheet workSheet, int column, int row, String s)
throws WriteException {
Label label;
label = new Label(column, row, s, timesBoldUnderline);
workSheet.addCell(label);
}
5. Add values to sheet
public void writeToSheet(String value) throws WriteException,
IOException, BiffException {
Workbook workbook = Workbook.getWorkbook(myFile);
WritableWorkbook copy = Workbook.createWorkbook(myFile, workbook);
WritableSheet workSheet = copy.getSheet(0);
int currentRowIndex = workSheet.getRows();
addValueToSheet(workSheet, 0, currentRowIndex, value);
copy.write();
copy.close();
}private void addValueToSheet(WritableSheet workSheet, int column, int row, String s)
throws WriteException {
Label label;
label = new Label(column, row, s, times);
workSheet.addCell(label);
}
Done!