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

pinkon5k  于 12个月前  发布在  Android
关注(0)|答案(3)|浏览(90)

我在我的Android应用程序的购物车.我使用Firebase作为数据库。我想邮寄购物车项目作为CSV / Excel文件作为附件。

0kjbasz6

0kjbasz61#

首先,你必须从firebase获取所有数据。
Read Data From Firebase database
然后你必须从数据生成csv文件。
How to create a .csv on android
之后,您可以发送csv文件从其路径作为附件的邮件
How to send an email with a file attachment in Android

kkih6yb8

kkih6yb82#

首先在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)
afdcj2ne

afdcj2ne3#

将此添加到您的构建中。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%有效。请根据自己的需要自由填写修改。

相关问题