簡體   English   中英

使用 C# 顯示來自 Excel 的數據

[英]Show Data from Excel Using C#

我的代碼在這里,但我無法獲得所需的結果

            DataTable dtWB = new DataTable();
            dtWB.Columns.Add("Name");
            dtWB.Columns.Add("DOS");
            dtWB.Columns.Add("CPT");
            dtWB.AcceptChanges();
            DataRow drWB = null;

            // Auto-detect format, supports:
            byte[] ExcelData = File.ReadAllBytes(AppDomain.CurrentDomain.BaseDirectory + path);
            MemoryStream stream = new MemoryStream(ExcelData);
            using (var reader = ExcelReaderFactory.CreateReader(stream))
            {
                // Choose one of either 1 or 2:

                // 1. Use the reader methods
                do
                {
                    while (reader.Read())
                    {
                        // reader.GetDouble(0);
                    }
                } while (reader.NextResult());

                // 2. Use the AsDataSet extension method
                var result = reader.AsDataSet();

                //The result of each spreadsheet is in result.Tables
                var Tables = result.Tables;
                var CT = Tables.Count;
                DataTable WBdt = Tables[1];
    }

我在 excel 表中有一個數據,例如https://i.stack.imgur.com/nZl4K.png

我想使用 c# 顯示這樣的數據。 https://i.stack.imgur.com/BjzZd.png

您的“代碼”僅包含ExcelDataReader文檔示例。 這會將數據集解析為具有您請求的格式的集合。

var records = new Dictionary<string, Dictionary<DateTime, double?>>();

using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
{
    using (var reader = ExcelReaderFactory.CreateReader(stream))
    {
        var firstTable = reader.AsDataSet().Tables[0];

        for (int i = 1; i < firstTable.Rows.Count; i++)
        {
            string name = firstTable.Rows[i].Field<string>(0);
            var dt_values = new Dictionary<DateTime, double?>();

            for (int j = 1; j < firstTable.Columns.Count; j++)
            {
                DateTime dt = firstTable.Rows[0].Field<DateTime>(j);
                double? value = firstTable.Rows[i].Field<double?>(j);
                dt_values.Add(dt, value);
            }

            records.Add(name, dt_values);
        }
   }
}

var formatted_data = records.SelectMany(x => x.Value.Select(y => new
{
    Name = x.Key,
    Dos = y.Key.ToShortDateString(),
    CPT = y.Value
}));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM