This question already has an answer here:
convert json to excel in java
(1 answer)
Closed 8 months ago.
I am new to Android Dev,This is my first Question in SO. i try to export my reports in Excel format. so i try to create the Excel file.Here is the code.
I am struck with get the json and put into the ROW and CELL
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView hwtxt = (TextView)findViewById(R.id.hw);
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet firstSheet = workbook.createSheet("Sheet1");
String url = "http://192.168.1.13:8090/Sanjay_API/showBalanceAmtList.php";
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("hwtxt", hwtxt.getText().toString()));
try {
JSONObject parentObject = new JSONObject(getJSONUrl(url, params));
JSONArray data = parentObject.getJSONArray("balance_list");
MyArrList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
String myVal1 = c.getString("entry_date");
System.out.println(myVal1);
}
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileOutputStream fos = null;
try {
String str_path = Environment.getExternalStorageDirectory().toString();
File file;
//String CurrentDateAndTime = java.text.DateFormat.getDateTimeInstance().format(new Date());
file = new File(str_path, getString(R.string.app_name) + ".xls");
fos = new FileOutputStream(file);
workbook.write(fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Toast.makeText(MainActivity.this, "Excel Sheet Generated", Toast.LENGTH_SHORT).show();
}
}
public String getJSONUrl(String url,List<NameValuePair> params) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Download OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download result..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
And, I have a data in json which is return from APT using PHP, My json is
{
"vnumber": [{
"vid": "1",
"vnumber": "STAT01",
"vname": "STAT01",
"vyear": "2011",
"fcdate": "22/12/2017",
"insdate": "22/12/2017",
"perdate": "22/12/2017",
"gtax": "0123456",
"polcer": "TEST DEMO CERTIFY"
}, {
"vid": "2",
"vnumber": "STAT02",
"vname": "STAT02",
"vyear": "2015",
"fcdate": "12/12/2012",
"insdate": "12/12/2012",
"perdate": "12/12/2012",
"gtax": "100",
"polcer": "100"
}]
}
I dont know how to export my data in excel format in SD Card.
Can you please try following.
File csvFile = new File(directory, Utils.CSV_FILE_NAME);
try {
csvFile.createNewFile();
CSVWriter csvWrite = new CSVWriter(new FileWriter(csvFile));
String heading[] = {"vid", "vnumber", "vname", "vyear", "fcdate", "insdate", "perdate", "gtax", "polcer"};
csvWrite.writeNext(heading);
for (int i = 0; i < arrayList.size(); i++) {
YourModel model = arrayList.get(i); // You can also use JsonObject from Json array.
String arrStr[] = {String.valueOf(model.getVid()), String.valueOf(model.getVnumber()), model.getVname(), model.getVyear(), model.getFcdate(), model.getInsdate(), model.getPerdate(),model.getGtax(), model.getPolcer() };
csvWrite.writeNext(arrStr);
}
csvWrite.close();
} catch (Exception sqlEx) {
Log.e(TAG, sqlEx.getMessage(), sqlEx);
}
Android is basically Java. Here is one question on Stackoverflow itself that can help you with this
convert json to excel in java
I have spent too much time for this implementation and finally below code is working for me
Add the following dependency in build.gradle
implementation 'org.apache.poi:poi:3.17'
Use the following code for Convert Java Object into Excel Cells and Row and finally create an excel file and download it to your phone storage.
HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
HSSFSheet hssfSheet = hssfWorkbook.createSheet("Custom Sheet");
//---------------
HSSFRow hssfRowMainTitle = hssfSheet.createRow(0);
hssfRowMainTitle.createCell(0).setCellValue("Document");
//-------------
HSSFRow hssfRowTitle = hssfSheet.createRow(1);
hssfRowTitle.createCell(0).setCellValue("srno");
hssfRowTitle.createCell(1).setCellValue("date");
hssfRowTitle.createCell(2).setCellValue("type");
hssfRowTitle.createCell(3).setCellValue("transactionid");
//--------------
int row = 2;
int srNo = 1;
for (Ledger a : currentFilterDataList) {
HSSFRow hssfRow = hssfSheet.createRow(row);
hssfRow.createCell(0).setCellValue(srNo);
hssfRow.createCell(1).setCellValue(a.getDate());
hssfRow.createCell(2).setCellValue(a.getType());
hssfRow.createCell(3).setCellValue(a.getVoucherNo());
row++;
srNo++;
}
//---------
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS + File.separator);
File file = new File(path.toString());
file.mkdirs();
String fileName = path + "/" + "transaction_" + System.currentTimeMillis() + ".xls";
try {
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
hssfWorkbook.write(fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
showSnackBar(getContext(), mBinding.getRoot(), "File downloaded successfully \n " + path);
} catch (IOException e) {
e.printStackTrace();
}
Related
I am trying to save data into a text file that does not yet exist online, but my urlConnection.getResponseCode() is returning a 404. I can read from files with similar urls, so I'm pretty certain the url is correct, but I've never written to an online file before.
private class SaveFile extends AsyncTask<String, Void, String> {
private String scheme = "http";
private String authority = "172.16.0.45";
private String path1 = "PrivateFile";
private String path2 = "SavedInstances";
protected void onPreExecute() {
}
protected String doInBackground(String...params) {
String result = null;
String filename = params[0] + ".txt";
String location = params[1];
OutputStream outStream = null;
HttpURLConnection urlConnection = null;
try {
// Save online as opposed to internal storage
if (location.equals("on")) {
Uri.Builder builder = new Uri.Builder();
builder.scheme(scheme);
builder.authority(authority);
builder.appendPath(path1);
builder.appendPath(path2);
builder.appendPath(filename);
String _url = builder.build().toString();
URL url = new URL(_url);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
if (urlConnection.getResponseCode() != 200) // Runs as true
throw new IOException(Integer.toString(urlConnection.getResponseCode()));
else {
outStream = urlConnection.getOutputStream();
}
} else if (location.equals("in")) {// Saving to internal
File file = new File(getFilesDir(), filename);
outStream = new FileOutputStream(file);
}
// Writing the file
PrintWriter writer = new PrintWriter(outStream);
writer.println(utils.size());
writer.println(trans.size());
writer.println(cables.size());
for (int i = 0; i < utils.size(); i++)
writer.println(utils.get(i).getValues());
for (int i = 0; i < trans.size(); i++)
writer.println(trans.get(i).getValues());
for (int i = 0; i < cables.size(); i++)
writer.println(cables.get(i).getValues());
writer.close();
outStream.close();
if (urlConnection != null)
urlConnection.disconnect();
result = "Save Successful";
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
} catch (MalformedURLException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
result = e.getMessage();// 404
System.out.println(e.getMessage());
}
return result;
}
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(),result,Toast.LENGTH_SHORT).show();
}
}
When I send the exception with getResponseMessage() instead, the message is "not found". What am I missing to get this connection working?
I am trying to save this boolean array. When I read the array the string array (parts) says that
parts[0]=true;
,but when I use Boolean.parseBoolean array[0] is still false. Can someone help me and tell me what I am doing wrong. Please and Thank You.
public void writeArraytofile() {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("array.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(Arrays.toString(array));
outputStreamWriter.close();
} catch (IOException e) {
Log.v("MyActivity", e.toString());
}
}
public boolean[] read(){
String result = "";
boolean[] array = new boolean[2];
try {
InputStream inputStream = openFileInput("array.txt");
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String tempString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((tempString = bufferedReader.readLine()) != null) {
stringBuilder.append(tempString);
}
inputStream.close();
result = stringBuilder.toString();
String[] parts = result.split(" ");
for (int i = 0; i < array.length; i++){
array[i]=Boolean.parseBoolean(parts[i]);
}
}
} catch (FileNotFoundException e) {
Log.v("MyActivity", "File not found" + e.toString());
} catch (IOException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
//here you catch and watch the problem
Log.e("MyActivity", "cant parse string: " + result);
}
return array;
}
Arrays.toString() will print brackets and commas, so when you read the string back in and call .split(" "), the first piece will be "[true,". Since that is not just "true", Boolean.parseBoolean() will return false.
I have this type of JSON:
{
"stampi":
[
{
"nome": "Ovale Piccolo 18.2x13.5cm",
"lunghezza": 18.2,
"larghezza": 13.5,
"altezza": 4,
"volume": 786.83
},
{
"nome": "Ovale Grande 22.5x17.4cm",
"lunghezza": 22.5,
"larghezza": 17.4,
"altezza": 4,
"volume": 1246.54
}
]
}
and normally I read with this code:
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open("stampi.json")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
myjson_stampi = sb.toString();
and after use the array inside the program.
I have create a menu that add new value inside the JSON file but i have a problem ...this is the code:
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open("stampi.json")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
myjson_stampi = sb.toString();
try {
// Creating JSONObject from String
JSONObject jsonObjMain = new JSONObject(myjson_stampi);
// Creating JSONArray from JSONObject
JSONArray objNames = jsonObjMain.names();
System.out.println(objNames.toString());
jsonArray_stampi = jsonObjMain.getJSONArray("stampi");
int num_elem = jsonArray_stampi.length();
jsonObjMain.put( "nome","prova");
jsonObjMain.put( "lunghezza",22);
jsonObjMain.put( "larghezza", 10);
jsonObjMain.put( "altezza", 4);
jsonObjMain.put( "volume", 10.5);
jsonArray_stampi.put( jsonObjMain );
try {
FileWriter file = new FileWriter("c:\\test.json");
//file.write(jsonArray_stampi.);
file.write( JSON.stringify(jsonArray_stampi) );
file.flush();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} });
why can't work correctly?
the num_elem variable are 2 always..help me!
thx Andrea
You have to create a new JSONObject and then add new data to it and then append to the existing object.
JSONObject jsonObjMain = new JSONObject(myjson_stampi); //Your existing object
JSONObject jO = new JSONObject(); //new Json Object
JSONArray jsonArray_stampi = jsonObjMain.getJSONArray("stampi"); //Array where you wish to append
//Add data
jO.put( "nome","prova");
jO.put( "lunghezza",22);
jO.put( "larghezza", 10);
jO.put( "altezza", 4);
jO.put( "volume", 10.5);
//Append
jsonArray_stampi.put(jO);
Also you should write back the complete jsonObject back to the file.
file.write(JSON.stringify(jsonObjMain));
Looks like you're trying to write to a file called c:\\test.json. Try using the proper Android way to write to files with openFileOutput. Examples are here.
String filename = "myfile";
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
The code below generates correctly the first structure of the json file.
gson = new GsonBuilder().setPrettyPrinting().create();
AudDetHeader AudDetHeader = new AudDetHeader();
//ArrayList<OrderDetail> AudDetList = new ArrayList<OrderDetail>();
Map<String, AudDet> AudDetList = new HashMap<String, AudDet>();
AudDet AudDet = new AudDet();
AudDet.setLineId("1");
AudDet.setItemNumber("ABC");
AudDet.setQuantity(9);
AudDet.setPrice(10.00);
List<String> phones = new ArrayList<String>();
phones.add("24530001");
phones.add("24530002");
phones.add("24530003");
AudDet.setPhones(phones);
AudDetList.put("teste 2", AudDet);
AudDetHeader.setAudDetList(AudDetList);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonString = gson.toJson(AudDetHeader);
BufferedWriter bufferedWriter = null;
try {
File file = new File(Environment.getExternalStorageDirectory() + "/download/test/test.json");
if(!file.exists()){
file.createNewFile();
}
FileWriter fileWriter = new FileWriter(file);
bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(jsonString);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bufferedWriter != null){
bufferedWriter.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
The result of the code:
{
"Results": {
"teste 2": {
"itemNumber": "ABC",
"lineId": "1",
"phones": [
"24530001",
"24530002",
"24530003"
],
"price": 10.0,
"quantity": 9
}
}
}
I want to add a new item. My desire is to stay as the structure below.
{
"Results":{
"teste 2":{
"itemNumber":"ABC",
"lineId":"1",
"phones":[
"24530001",
"24530002",
"24530003"
],
"price":10.0,
"quantity":9
},
"teste 3":{
"itemNumber":"DEF",
"lineId":"2",
"phones":[
"30303030",
"40404040",
"505050"
],
"price":11.0,
"quantity":12
}
}
}
The AudDetHeader.class
public class AuditoriaDetalheHeader {
#SerializedName("Results")
private Map<String, AuditoriaDetalhe> AuditoriaDetalheList;
...
}
The AudDet.class
public class AuditoriaDetalhe {
String lineId = null;
String itemNumber = null;
int quantity = 0;
Double price = null;
List<String> phones = new ArrayList<String>();
...
}
Worked for me with this code!!!
Main class
private static File fileJson = new File(Environment.getExternalStorageDirectory() + "/download/test/test.json");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.teste_criajson);
createJsonStructure();
Button btnSave = (Button)findViewById(R.id.btSave);
btnSalvar.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
try {
String strFileJson = getStringFromFile(fileJson.toString());
JSONObject jsonObj = new JSONObject(strFileJson);
Gson gson = new Gson();
JsonParser jsonParser = new JsonParser();
String idAud = "10";
AudDet ad = new AudDet();
ad.setLineId("2");
ad.setItemNumber("DEF");
ad.setQuantity(22);
ad.setPrice(22.22);
List<String> phones = new ArrayList<String>();
phones.add("22");
phones.add("22");
phones.add("22");
ad.setPhones(phones);
String jsonStr = jsonParser.parse(gson.toJson(ad)).toString();
JSONObject JSONObject = new JSONObject(jsonStr);
jsonObj.getJSONObject("Results").put(idAud, JSONObject);
writeJsonFile(fileJson, jsonObj.toString());
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
If do not exists json file, then i create with basic structure for insert the itens.
public static void createJsonStructure(){
if(!fileJson.exists()){
try {
fileJson.createNewFile();
String jsonString = "{\"Results\":{}}";
writeJsonFile(fileJson, jsonString);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Open the json file to get the string format, and prepare to insert a new item:
public static String getStringFromFile (String filePath) throws Exception {
File fl = new File(filePath);
FileInputStream fin = new FileInputStream(fl);
String ret = convertStreamToString(fin);
//Make sure you close all streams.
fin.close();
return ret;
}
public static String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
return sb.toString();
}
Writes into the json file that already exists:
public static void writeJsonFile(File file, String json)
{
BufferedWriter bufferedWriter = null;
try {
if(!file.exists()){
file.createNewFile();
}
FileWriter fileWriter = new FileWriter(file);
bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(json);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bufferedWriter != null){
bufferedWriter.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
hey there guys and girls i have this code that saves json as a string representation, i still haveing a little trouble understanding how the entity section works, and need to know how to change my code so that it works, this is the error im getting,
Error saving string java.lang.NumberFormatException: unable to parse '[{"story_name":"Story One"},{"story_name":"Story Two"},{"story_name":"Story Three"},{"story_name":"Story Four"},{"story_name":"Story Five"},{"story_name":"Story Six"}]' as integer
i was getting help from someone last night that almost got me there but still need a little more understanding of how it works and wht i get the parse error here is my full code
public class MainActivity extends Activity {
String entityString = null;
String storyObj = "";
Object json = null;
HttpEntity entity = null;
InputStream is = null;
Integer responseInteger = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//button that saves the file from mySQL
Button save = (Button) findViewById(R.id.downloadBtn);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveJson();
}
});
//Button that opens the file from InternalMemory
Button open = (Button) findViewById(R.id.showBtn);
open.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openJson();
}
});
//end of onCreate()
}
//saveJson pull a JSON file from mySQl server then saves that file in its JSON type eg .json
public void saveJson(){
TextView test = (TextView) findViewById(R.id.showView);
try{
//connects to mySQL
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://10.0.2.2/textures_story_list.php");
HttpResponse response = client.execute(post);
//captures the response
entity = response.getEntity();
InputStream entityStream = entity.getContent();
StringBuilder entityStringBuilder = new StringBuilder();
byte [] buffer = new byte[1024];
int bytesReadCount;
while ((bytesReadCount = entityStream.read(buffer)) > 0) {
entityStringBuilder.append(new String(buffer, 0, bytesReadCount));
}
entityString = entityStringBuilder.toString();
responseInteger = Integer.valueOf(entityString);
}catch(Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
}
try{
//is = entity.getContent();
String FILENAME = "story.json";
//gives file name
FileOutputStream output = openFileOutput(FILENAME, MODE_WORLD_READABLE);
//creates new StreamWriter
OutputStreamWriter writer = new OutputStreamWriter(output);
//writes json with file name story.json
writer.write(entityString);
writer.flush();
//closes writer
writer.close();
}catch(Exception e) {
Log.e("log_tag", "Error saving string "+e.toString());
}
//end of saveJson()
}
public void openJson(){
TextView test = (TextView) findViewById(R.id.showView);
try{
FileInputStream fileInput = openFileInput("story.json");
BufferedReader inputReader = new BufferedReader(new InputStreamReader(fileInput, "UTF-8"), 8);
StringBuilder strBuilder = new StringBuilder();
String line = null;
while ((line = inputReader.readLine()) != null) {
strBuilder.append(line + "\n");
}
fileInput.close();
storyObj = strBuilder.toString();
}catch(IOException e){
Log.e("log_tag", "Error building string "+e.toString());
}
try{
JSONArray jArray = new JSONArray(storyObj);
String storyNames = "";
for(int i = 0;i<jArray.length();i++){
storyNames += jArray.getJSONObject(i).getString("story_name") +"\n";
}
test.setText(storyNames);
}catch(JSONException e) {
Log.e("log_tag", "Error returning string "+e.toString());
}
return;
//and of openJson()
}
//end of class body
}
My guess it your code failed at this lines:
responseInteger = Integer.valueOf(entityString);
After a little inspection, I see that your JSON is:
[{"story_name":"Story One"},{"story_name":"Story Two"},{"story_name":"Story Three"},{"story_name":"Story Four"},{"story_name":"Story Five"},{"story_name":"Story Six"}]
A closer inspection using JSON Viewer, I see that your structure is like this:
The problem is
I don't see any integer in this JSON. You might have to use a combination of JSONObject and JSONArray to parse your it properly.
Your problem is this line
responseInteger = Integer.valueOf(entityString);
entityString is
'[{"story_name":"Story One"},{"story_name":"Story Two"},{"story_name":"Story Three"},{"story_name":"Story Four"},{"story_name":"Story Five"},{"story_name":"Story Six"}]'
And when Integer.valueOf tries to parse it, it can't parse it as an integer, so it throws a NumberFormatException.
Sample JSon string:
{
Stories:
[
{
"story_name": "Story One"
},
{
"story_name": "Story Two"
}
]
}
Create a Class:
public class Story
{
public String stort_name;
}
class CollectionOfStories
{
public List<Story> Stories;
public CollectionOfSections()
{
Stories= new ArrayList<Story>();
}
}
Finally:
private CollectionOfStories convertDataFromJSonToObject(String jsonString)
{
JSONObject jso;
CollectionOfStories colStories = new CollectionOfStories();
try
{
jso = new JSONObject(jsonString);
JSONArray ja = jso.getJSONArray("Stories");
for (int i = 0; i < ja.length(); i++)
{
Story s = new Story();
JSONObject jsonSection = ja.getJSONObject(i);
s.stort_name = jsonSection.getString("story_name");
//add it to sections list
colStories.Stories.add(s);
}
}
catch (NumberFormatException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return colStories;
}