在互联网上搜索了很多后,我得到了在 android App 中创建 Csv 文件的解决方案,
内部存储(不带 SD 卡),所以我决定与其他人分享如何在 android 中创建 csv 文件以及如何将其附加到邮件中。
首先下载Opencsv.jar 库并添加到您的android 项目中。 https://sourceforge.net/projects/opencsv/files/opencsv/
直接添加实现(.jar不用下载)
implementation 'com.opencsv:opencsv:4.6' // Here is opencsv library
或者在android项目中添加jar文件:
- 将 Android Studio 文件结构 Android 更改为 Project(在项目名称 Android 的左下方,更改为 Project)
- 复制
opencsv.jar文件并粘贴到libs文件夹中。
- 右击
opencsv.jar文件并点击Add as library。
向 Menifest.xml 添加权限(如果设备 API 为 23 或更高,请检查运行时权限)
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
打开 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
}
现在编码部分:创建 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();
}
}
});
现在,如果您想在 android 中查看您的 csv 文件,请按照以下步骤操作:
- 转到文件管理器/我的文件到您的手机。
- 转到内部存储/本地,只需滚动即可获得 csv 文件。
- 如果 csv 文件未在您的设备中打开,请从 Play 商店安装 Csv Viewer。
现在,如果您想将此 csv 文件通过附件附加到您的应用中
以下是邮件中 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@example.com"});
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"));
}
});