如何在 android 上创建 .csv
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11341931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a .csv on android
提问by Kunal Shah
My aim is to create a .csv file from a table, to print a report. I can then store this .csv file into my sdCard. I have referred to some questions similar to this but they ask a jar file to be present. Is there any other way without a jar file to be integrated?
我的目标是从表格创建一个 .csv 文件,以打印报告。然后我可以将此 .csv 文件存储到我的 sdCard 中。我已经提到了一些与此类似的问题,但他们要求提供一个 jar 文件。有没有其他方法可以不集成 jar 文件?
Have integrate a jar file in the component au.com.bytecode.opencsv.CSVWriter...What I dont find here is the logic to write into a new line...Help?
在组件 au.com.bytecode.opencsv.CSVWriter 中集成了一个 jar 文件......我在这里找不到的是写入新行的逻辑......帮助?
回答by Dhaval Parmar
check below code to generate CSV file. no need to use jar file.
检查以下代码以生成 CSV 文件。不需要使用 jar 文件。
you have to save one csv file in to SD-CARD.
您必须将一个 csv 文件保存到 SD-CARD 中。
public void exportEmailInCSV() throws IOException {
{
File folder = new File(Environment.getExternalStorageDirectory()
+ "/Folder");
boolean var = false;
if (!folder.exists())
var = folder.mkdir();
System.out.println("" + var);
final String filename = folder.toString() + "/" + "Test.csv";
// show waiting screen
CharSequence contentTitle = getString(R.string.app_name);
final ProgressDialog progDailog = ProgressDialog.show(
MailConfiguration.this, contentTitle, "even geduld aub...",
true);//please wait
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
}
};
new Thread() {
public void run() {
try {
FileWriter fw = new FileWriter(filename);
Cursor cursor = db.selectAll();
fw.append("No");
fw.append(',');
fw.append("code");
fw.append(',');
fw.append("nr");
fw.append(',');
fw.append("Orde");
fw.append(',');
fw.append("Da");
fw.append(',');
fw.append("Date");
fw.append(',');
fw.append("Leverancier");
fw.append(',');
fw.append("Baaln");
fw.append(',');
fw.append("asd");
fw.append(',');
fw.append("Kwaliteit");
fw.append(',');
fw.append("asd");
fw.append(',');
fw.append('\n');
if (cursor.moveToFirst()) {
do {
fw.append(cursor.getString(0));
fw.append(',');
fw.append(cursor.getString(1));
fw.append(',');
fw.append(cursor.getString(2));
fw.append(',');
fw.append(cursor.getString(3));
fw.append(',');
fw.append(cursor.getString(4));
fw.append(',');
fw.append(cursor.getString(5));
fw.append(',');
fw.append(cursor.getString(6));
fw.append(',');
fw.append(cursor.getString(7));
fw.append(',');
fw.append(cursor.getString(8));
fw.append(',');
fw.append(cursor.getString(9));
fw.append(',');
fw.append(cursor.getString(10));
fw.append(',');
fw.append('\n');
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
// fw.flush();
fw.close();
} catch (Exception e) {
}
handler.sendEmptyMessage(0);
progDailog.dismiss();
}
}.start();
}
}
add this permission in manifest
在清单中添加此权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
回答by Abhishek kumar
After searching lots over internet i got solution of creating Csv file inside android App, internal storage (without SD Card), So i decided to share with others how to create csv file in android & How to attach it with mail.
在互联网上搜索了很多之后,我得到了在 android 应用程序、内部存储(没有 SD 卡)中创建 csv 文件的解决方案,所以我决定与其他人分享如何在 android 中创建 csv 文件以及如何将其附加到邮件中。
First Download Opencsv.jar
library and add to your android project. https://sourceforge.net/projects/opencsv/files/opencsv/
首先下载Opencsv.jar
库并添加到您的android项目中。https://sourceforge.net/projects/opencsv/files/opencsv/
Add the implementation directly (no download of .jar
)
直接添加实现(无需下载.jar
)
implementation 'com.opencsv:opencsv:4.6' // Here is opencsv library
Or add jar file in android project :
或者在android项目中添加jar文件:
- Change Android Studio file structure Android to Project ( At Top Left below of Project Name Android,change to Project)
- Copy
opencsv.jar
file and paste inlibs
folder. - Right click
opencsv.jar
file and hitAdd as library
.
- 将 Android Studio 文件结构 Android 更改为 Project(在项目名称 Android 的左下方,更改为 Project)
- 复制
opencsv.jar
文件并粘贴到libs
文件夹中。 - 右键单击
opencsv.jar
文件并点击Add as library
。
Add permission to Menifest.xml( If device API is 23 or greater Check RunTime Permission)
向 Menifest.xml 添加权限(如果设备 API 为 23 或更高,请检查运行时权限)
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Open build.gradle (Module:app)and check it added :
打开build.gradle (Module:app)并检查它是否添加:
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:26.+'
compile 'com.google.code.gson:gson:2.2.4'
compile 'com.android.support:recyclerview-v7:26.+'
testCompile 'junit:junit:4.12'
implementation files('libs/opencsv-4.1.jar') // Here is opencsv library added to project when using .jar
}
Now coding part : Creating csv file and inserting data into it.
现在编码部分:创建 csv 文件并将数据插入其中。
String csv = (Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyCsvFile.csv"); // Here csv file name is MyCsvFile.csv
//by Hiting button csv will create inside phone storage.
buttonAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
CSVWriter writer = null;
try {
writer = new CSVWriter(new FileWriter(csv));
List<String[]> data = new ArrayList<String[]>();
data.add(new String[]{"Country", "Capital"});
data.add(new String[]{"India", "New Delhi"});
data.add(new String[]{"United States", "Washington D.C"});
data.add(new String[]{"Germany", "Berlin"});
writer.writeAll(data); // data is adding to csv
writer.close();
callRead();
} catch (IOException e) {
e.printStackTrace();
}
}
});
Now if you want to view your csv file inside the androidfollow below steps:
现在,如果您想在 android 中查看您的 csv 文件,请按照以下步骤操作:
- Go to File Manager/ My Files to your phone.
- Go to internal storage/ Local , just scroll you will get your csv file.
- If csv file is not opening in your device install Csv Viewerfrom Play Store.
- 转到文件管理器/我的文件到您的手机。
- 转到内部存储/本地,只需滚动即可获得 csv 文件。
- 如果 csv 文件未在您的设备中打开,请从 Play 商店安装 CSV查看器。
Now, If you want to attach this csv file to your app with attachment
现在,如果您想将此 csv 文件附加到您的应用程序
Here is the code for attachment of csv file in mail :
这是邮件中 csv 文件附件的代码:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("text/plain");
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{"[email protected]"});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "subject here");
emailIntent.putExtra(Intent.EXTRA_TEXT, "body text");
File file = new File(csv);
Uri uri = Uri.fromFile(file);
emailIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(emailIntent, "Pick an Email provider"));
}
});
回答by Khurram
this will work :)
这将工作:)
try {
String TestString="";
FileOutputStream fOut = openFileOutput(filename, MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
// Write the string to the file
for( i=1; i<total_row; i++)
{
for( j=1; j<total_col; j++)
{
TestString+=table[i][j].getText().toString(); // to pass in every widget a context of activity (necessary)
TestString += " ,";
}
TestString+="\n";
}
Log.v("the string is",TestString);
osw.write(TestString);
osw.flush();
osw.close();
}
catch (IOException ioe)
{ioe.printStackTrace();}
in manifest u would have to write
在清单中你必须写
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
just before the application tag
就在应用程序标签之前