简体   繁体   English

如何从 Android Studio 表布局生成 CSV 文件

[英]How to generate CSV file from Android Studio Table Layout

I'm developing an android app which store user input in SQLite database.我正在开发一个 android 应用程序,它将用户输入存储在 SQLite 数据库中。 and displays it in TableLayout in android studio.并将其显示在 android 工作室的 TableLayout 中。 Now I want to generate CSV file from the contents of that Table Layout.现在我想从该表格布局的内容中生成 CSV 文件。

I need a button to generate the CSV file.我需要一个按钮来生成 CSV 文件。 Thanks in advance.提前致谢。 I'm new to StackoverFlow and coding.我是 StackoverFlow 和编码的新手。 So forgive me If my question wasn't right.如果我的问题不正确,请原谅我。

I really need this code to complete my project.我真的需要这段代码来完成我的项目。 Thanks in Advance.提前致谢。

hello here is my sample simple code for creating csv from database,你好,这是我从数据库创建 csv 的示例简单代码,

codes read data by Database_helper and put fetched data inside an arrayList then put every item of arrayList inside of csvfile (csvFile.csv) and store for creating csv you need follow this format for every row of csvFile < item1;item_2;item_3;...;item_n> every column seprate by;(semicolon) and write in a file whit.csv type NOTICE: this code works in android version 6 (for android 11 need another methods for creating file in storage but main concept for creating csv is same as this code) codes read data by Database_helper and put fetched data inside an arrayList then put every item of arrayList inside of csvfile (csvFile.csv) and store for creating csv you need follow this format for every row of csvFile < item1;item_2;item_3;.. .;item_n> every column seprate by;(semicolon) and write in a file whit.csv type NOTICE: this code works in android version 6 (for android 11 need another methods for creating file in storage but main concept for creating csv is same作为这个代码)

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteException;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

public class CsvMaker extends AppCompatActivity {
    ArrayList<NewsInformation> news = new ArrayList<>();
    private DatabaseHandler db;
    Button csv_maker;
    TextView txt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_csv_maker);

        csv_maker = (Button) findViewById(R.id.csv_maker);
        txt = (TextView) findViewById(R.id.csv_address);

        csv_maker.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hasStoragePermission(1);
            }
        });


    }

    public void createCsv() {
        db = new DatabaseHandler(this);
        try {
            db.open();
            ArrayList<NewsInformation> news = db.getAllNews();
            db.close();
            exportTheDB();

        } catch (SQLException | IOException throwables) {
            throwables.printStackTrace();

        }
    }


    private void exportTheDB() throws IOException {
        File myFile;
        try {

            myFile = new File(Environment.getExternalStoragePublicDirectory(""), "csvFile.csv");
            myFile.createNewFile();
            FileOutputStream fOut = new FileOutputStream(myFile);
            OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
            myOutWriter.append("News_Description;News_Image;News_link;News_Title");
            myOutWriter.append("\n");


            for (int i = 0; i < news.size(); ++i) {
                String description = news.get(i).description;
                String image = news.get(i).image;
                String link = news.get(i).link;
                String title = news.get(i).title;
                myOutWriter.append(description + ";" + image + ";" + link + ";" + title);
                myOutWriter.append("\n");
            }


            myOutWriter.close();
            fOut.close();
            txt.setText(myFile.getAbsolutePath());


        } catch (SQLiteException se) {
            Log.e(getClass().getSimpleName(), "Could not create or Open the database");
        }


    }

    private void hasStoragePermission(int requestCode) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                //  return false;
            } else {
                createCsv();
                // return true;
            }
        } else {
            //return true;
            createCsv();
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            if (requestCode == 1) {
                createCsv();
            }


        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM