【HarmonyOS NEXT】鸿蒙应用加载读取csv文件 原创

George_wu_
发布于 2025-3-24 15:41
浏览
0收藏

【HarmonyOS NEXT】鸿蒙应用加载读取csv文件

一、问题背景:

1. csv文件是什么?
csv是一种文本文件格式,与json类似。会存储一些文本内容,应用需要读取该文件,进行UI内容得填充等。
文件中的数据是以纯文本形式存储的,并且数据行和字段之间通过特定的分隔符(通常是逗号)分隔。
2. CSV 文件示例

xx.csv
姓名,年龄,城市
张三,28,北京
李四,34,上海
王五,22,广州

数据结构:
export default class TestObj{
  name: string = "";
  age: string = "";
  city: string = "";
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.

在上面得示例中:

第一行是表头,定义了三个字段:姓名、年龄和城市。
接下来的三行是数据记录,每行包含一条记录。
字段之间用逗号分隔。

二、解决方案:

1. 方式一:
使用三方提供得SDK进行csv文件得解析:
“@ohos/opencsv”: “2.0.0”

import { getPath, openSync,CSVReaderBuilder,CSVParser } from '@ohos/opencsv';
getPath().then((path) => {
    let rd = openSync (path,'test.csv'/* csv filename */,0o2)
    let readerBuilder: CSVReaderBuilder = new CSVReaderBuilder(rd)
    let readerbuildcsv = readerBuilder
          .withCSVParser(new CSVParser())
          .buildCSVReader()
    let lines: Array<Array<string>> = null;
    lines = readerbuildcsv.readAll() // Read all data in the CSV file.
    console.log(lines)
    /* [
     *  [1,'Zhang San',18]
     *  [2,'Li Si',19]
     *  [3,'Wang Wu', 20]
     *  [4,'Zhao Liu', 21]
     *               ]
     */
    readerbuildcsv.close () // Close reading.
})
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.

2. 方式二:

  private parseCsvToStrings(csvString: string, delimiter = ','): Array<TestObj> {
    const lines = csvString.trim().split('\n');
    const headers = lines[0].split(delimiter);
    // 将object替换为你的目标对象类型
    const data: Array<TestObj> = new Array();

    for (let i = 1; i < lines.length; i++) {
      const values = lines[i].split(delimiter);
      const row: TestObj = new TestObj();
      headers.forEach((header, index) => {
        let res: string = values[index]?.trim()?.toString() || '';
        switch (header.trim()){
          case "name":
            row.name = res;
            break;
          case "age":
            row.name = res;
            break;
          case "city":
            row.name = res;
            break;
        }
      });
      data.push(row);
    }
    return data;
  }
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.

注意:
对于大型CSV文件,手动解析可能会比较慢,而使用优化的第三方库可能会更快。

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
标签
收藏
回复
举报
回复
    相关推荐
    社区精华内容