最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Android - Export SQLite data to CSV with accents - Stack Overflow

programmeradmin1浏览0评论

I am trying to export date in my android app from SQLite database to CSV. But the data in database contains accents (diacritics) as they are in slovak language.

My export already works, but when I open the exported CSV in Google Sheets, the accents are showing wrongly. E.g. Á3/4 etc.

When I click š dots in opened CSV file in Google Sheets, it says I am using a Office compability and I can Save it in Google sheet format on Google drive. After I save it, the accents are fine, but I need to have the correct accents in the original CSV after the user exports it from my app.

This is what I tried:

public Uri exportCSV(Context context) {
        String fileName = "my_data.csv";
        ContentResolver resolver = context.getContentResolver();
        Uri fileUri = null;

        ContentValues values = new ContentValues();
        values.put(MediaStore.Downloads.DISPLAY_NAME, fileName);
        values.put(MediaStore.Downloads.MIME_TYPE, "text/csv");
        values.put(MediaStore.Downloads.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS + "/osiva_export");

        try {
            fileUri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values);
            if (fileUri == null) {
                return null;
            }

            OutputStream outputStream = resolver.openOutputStream(fileUri);
            if (outputStream == null) {
                return null;
            }

            // **Ensure UTF-8 encoding using BufferedWriter**
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));

            // **Write UTF-8 BOM (\uFEFF) to ensure Google Sheets detects encoding**
            writer.write("\uFEFF");

            // **Write CSV Header**
            writer.write("Názov rastliny;Výrobca;\n");

            SQLiteDatabase db = this.getReadableDatabase();
            String query = "SELECT k.NAZOV, ...";

            Cursor cursor = db.rawQuery(query, null);

            while (cursor.moveToNext()) {
                String plantName = cursor.getString(0);
                String manufacturer = cursor.getString(1);
              

                // **Write CSV row**
                String line = plantName + ";" +
                        manufacturer + ";" +
                       "\n";

                writer.write(line);
            }

            cursor.close();
            writer.flush();
            writer.close();
            outputStream.close();

            Log.i("CSV Export", "File successfully created with UTF-8 encoding: " + fileUri.toString());
            return fileUri;

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

still not working as expected with accents.

发布评论

评论列表(0)

  1. 暂无评论