I'm trying to use Jexcel API to create an excel file and write to it using my application on my phone. When I run the app, it throws a FileNotFoundException
. I even tried creating a text file according to an answer to another such question, but it throws the same error. I have given the appropriate permissions in the manifest, but I still cant seem to pinpoint the problem.
Please help.
Here is my code
public WritableWorkbook createWorkbook(String fileName){
//Saving file in external storage
File sdCard = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File directory = new File(sdCard.getAbsolutePath() + "/bills");
//create directory if not exist
if(!directory.isDirectory()){
directory.mkdirs();
}
//file path
file= new File(directory, fileName);
if (file.exists())
Log.e(taf,"file created");
else
Log.e(taf,"file not created");
WorkbookSettings wbSettings = new WorkbookSettings();
wbSettings.setLocale(new Locale("en", "EN"));
wbSettings.setUseTemporaryFileDuringWrite(true);
WritableWorkbook workbook;
workbook=null;
try {
workbook = Workbook.createWorkbook(file, wbSettings);
Log.i(taf,"workbook created");
//Excel sheet name. 0 represents first sheet
WritableSheet sheet = workbook.createSheet("MyShoppingList", 0);
try {
sheet.addCell(new Label(0, 0, "Subject")); // column and row
sheet.addCell(new Label(1, 0, "Description"));
String title = "blaj";
String desc = "nxjdncj";
int i = 1;
sheet.addCell(new Label(0, i, title));
sheet.addCell(new Label(1, i, desc));
} catch (WriteException e) {
e.printStackTrace();
}
workbook.write();
try {
workbook.close();
} catch (WriteException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return workbook;
}
On executing, the log message " file not created " is printed. Im new to android so please point out even the most basic issues.
Thank you.
Instantiating File
does not create the file, just gives you a File
instance whether a file with that particular path and file name exists or not.
Check out the source code of the constructor:
public File(String dirPath, String name) {
if (name == null) {
throw new NullPointerException("name == null");
}
if (dirPath == null || dirPath.isEmpty()) {
this.path = fixSlashes(name);
} else if (name.isEmpty()) {
this.path = fixSlashes(dirPath);
} else {
this.path = fixSlashes(join(dirPath, name));
}
}
To actually create the file you could do something like this:
if (!file.exists()) {
// file does not exist, create it
file.createNewFile();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With