如何使用 Android 代码从 Firebase 生成 CSV/Excel 文件

问题描述 投票:0回答:3

我的 Android 应用程序中有购物车。我使用 Firebase 作为数据库。我想将购物车项目以 CSV/Excel 文件形式作为附件邮寄。

android firebase csv cart
3个回答
0
投票

首先,您必须从 firebase 获取所有数据。

从 Firebase 数据库读取数据

然后你必须从数据生成 csv 文件。

如何在Android上创建.csv

之后,您可以将 csv 文件从其路径作为邮件附件发送

如何在 Android 中发送带有文件附件的电子邮件


0
投票

首先在您的 firebase 项目中安装 excel4node 包,然后将其导入到您的 index.js 中

const xl = require('excel4node');

还导入这些用于文件处理

const os = require('os');
const path = require('path');
const fs = require('fs');
const tempFilePath = path.join(os.tmpdir(), 'Excel.xlsx');
const storage = admin.storage();
const bucket = storage.bucket();

这就是返回函数的样子

exports.writeFireToExcel = functions.https.onCall(async(data, context) => {

    // Create a new instance of a Workbook class
    const workbook = new xl.Workbook();
    // Add Worksheets to the workbook
    const worksheet = workbook.addWorksheet('Visa Work List');

    const ref = firebaseDb.ref('path');

    //firebase functions that return stuff must be done in a transactional way

    //start by getting snap
    return await ref.once('value').then(snapshot =>{

    var style = workbook.createStyle({
        font: {
          bold : true,
        },
      });

    //write workbook
        worksheet.cell(1, 1).string('input').style(style);
        //....write the rest of your excel
        return
        //
    }).then(function (){
        console.log('workbook filled');
        //second part of transation - write the excel file to the temp storage in firebase
        //workbook.write doesnt return a promise so ive turned it into a promise function
        return new Promise((resolve,reject) =>{
            workbook.write(tempFilePath, function (err, stats) {
                if (err) {
                    console.error(err);
                    reject(err)
                }else{
                    resolve()
                }
            });
        })
    }).then(function(){
        console.log("File written to: " + tempFilePath);
        //read the file and check it exists
        return new Promise((resolve,reject) =>{
            fs.readFile(tempFilePath, function (err, data) {
                if (err) {
                    reject(err)
                }else{
                    resolve()
                }
            })

        })

    }).then(function(){
        console.log("writing to bucket");
        //write the file to path in firebase storage 
        var fileName = 'VisaSummaryList.xlsx';
        var folderPath = uid + "/excelFile/";
        var filePathString = folderPath + fileName;

        return bucket.upload(tempFilePath, 
            { destination: filePathString}).then(function(){
                return filePathString;
            })

    }).catch(err => {
        throw err;
    });
});

该函数返回 Firebase 存储中的文件路径。在您的 Android 应用程序中只需:

 //firebase storage reference, result being whats returned from the firebase function
 val fbstore = FirebaseStorage.getInstance().reference.child(result)
 fbstore.getFile(myFile)

0
投票

将其添加到您的 build.gradle

implementation 'org.apache.poi:poi:5.2.2'
implementation 'org.apache.poi:poi-ooxml:5.2.2'

然后,创建一个像这样的数据类:

data class Readings(
val temp: String,
val hum: String,
val press: String,
val alt: String,
val timestamp: String
)

之后添加一个函数,类似如下:

fun export2Excel() {
val uid = FirebaseAuth.getInstance().currentUser?.uid

if (uid != null) {
    val firebaseData = FirebaseDatabase.getInstance().getReference("UserData").child(uid).child("readings")

    firebaseData.keepSynced(true)
    firebaseData.addValueEventListener(object : ValueEventListener {
        override fun onDataChange(snapshot: DataSnapshot) {
            val list = mutableListOf<Readings>()
            snapshot.children.forEach { timestampSnapshot ->
                val temp = timestampSnapshot.child("temperature").value.toString()
                val hum = timestampSnapshot.child("humidity").value.toString()
                val press = timestampSnapshot.child("pressure").value.toString()
                val alt = timestampSnapshot.child("altitude").value.toString()
                val timestamp = timestampSnapshot.child("timestamp").value.toString()

                list.add(Readings(temp, hum, press, alt, timestamp))
            }

            val file = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "data.xls")
            val workbook = Workbook.createWorkbook(file)
            val sheet = workbook.createSheet("Sheet1", 0)

            list.forEachIndexed { index, reading ->
                val timestampDate = Date(reading.timestamp.toLong() * 1000)
                val formattedTimestamp = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(timestampDate)
                val indexLabel = (index + 1).toString()

                sheet.addCell(jxl.write.Label(0, 0, ""))
                sheet.addCell(jxl.write.Label(1, 0, "Timestamp"))
                sheet.addCell(jxl.write.Label(2, 0, "Temperature (°C)"))
                sheet.addCell(jxl.write.Label(3, 0, "Humidity (%Rh)"))
                sheet.addCell(jxl.write.Label(4, 0, "Pressure (hPa)"))
                sheet.addCell(jxl.write.Label(5, 0, "Altitude (m)"))

                sheet.addCell(jxl.write.Label(0, index + 1, indexLabel))
                sheet.addCell(jxl.write.Label(1, index + 1, formattedTimestamp))
                sheet.addCell(jxl.write.Label(2, index + 1, reading.temp))
                sheet.addCell(jxl.write.Label(3, index + 1, reading.hum))
                sheet.addCell(jxl.write.Label(4, index + 1, reading.press))
                sheet.addCell(jxl.write.Label(5, index + 1, reading.alt))
            }

            workbook.write()
            workbook.close()

            Log.d("FB2ExcelViewModel", "Items: $list")
        }

        override fun onCancelled(error: DatabaseError) {}
    })
  }
}

给出的例子来自我的项目,它100%有效。 请根据自己的需要随意填写修改。

© www.soinside.com 2019 - 2024. All rights reserved.