NEWS

[C#] Đọc dữ liệu file data từ Spead Sheet Google Api v4

[C#] Đọc dữ liệu file data từ Spead Sheet Google Api v4
Đăng bởi: Thảo Meo - Lượt xem: 25173 15:20:31, 26/10/2018DEVEXPRESS   In bài viết

Xin chào, các bạn bài viết hôm nay mình sẽ hướng dẫn các bạn cách đọc dữ liệu trực tiếp từ file SpeadSheet của Google sử dụng Google Sheet Api version 4.

[C#] Read Data from google Sheet Api v4

Trong bài viết này, mình sẽ sử dụng thư viện google Sheet Api để đọc dữ liệu.

Nhiều lúc, các bạn có lưu thử một file excel trên google drive, và mình muốn đọc file excel đó và hiển thị lên ứng dụng C# winform của mình.

Đầu tiên, các bạn vào đường dẫn sau đây để tạo một project, khi tạo xong, google sẽ tạo cho chúng ta một file credentials.json để chúng ta copy pass vào project mình.

Và nhớ chọn chế độ là Copy Always.

Chi tiết cài đặt xem ở link này: https://developers.google.com/sheets/api/quickstart/dotnet

Dưới đây là giao diện ứng dụng đọc dữ liệu từ file excel ở trên google drive:

đọc file từ google excel online c#
Read file from google Spead sheet 

 

Các bạn có thể xem video demo ở đây:

Cách thực hiện:

Đầu tiên, từ Nuget các bạn import thư viện Google Api v4 vào.

Install-Package Google.Apis.Sheets.v4

Trong souce code này các bạn cần lưu ý cấu hình ở thông file này.

String spreadsheetId = "1NduTqEh0aKLm0ZP2XRSL2OGDMooWaTFWYVpmMbH7QZk";
String range = "Email!A2:B";

dòng ở trên là id của file spead sheet, bạn có thể xem id ở hình ảnh bên dưới.

và dòng dưới là tên Sheet và lấy dữ liệu từ ô A2 đến ô B.

read_google_speadsheet_csharp_hinh2

Và dưới đây là source code c# cho sự kiện nhấn nút click lấy dữ liệu từ file Excel Google.

using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Sheets.v4;
using Google.Apis.Sheets.v4.Data;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AccessSpeadSheetGoogle
{
    public partial class Form1 : Form
    {        
        static string[] Scopes = { SheetsService.Scope.SpreadsheetsReadonly };
        static string ApplicationName = "Demo Read Google SpeadSheet";
        public Form1()
        {
            InitializeComponent();
        }

        private void btn_get_Click(object sender, EventArgs e)
        {
            UserCredential credential;

            using (var stream =
                new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = "token.json";
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }
          
            var service = new SheetsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });

            // Define request parameters.
            String spreadsheetId = "1NduTqEh0aKLm0ZP2XRSL2OGDMooWaTFWYVpmMbH7QZk";
            String range = "Email!A2:B";
            SpreadsheetsResource.ValuesResource.GetRequest request =
                    service.Spreadsheets.Values.Get(spreadsheetId, range);
                    
            // https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit

            ValueRange response = request.Execute();
            IList<IList<Object>> values = response.Values;
            if (values != null && values.Count > 0)
            {
                ListViewItem item = new ListViewItem();
                foreach (var row in values) 
                {                    
                    Console.WriteLine("{0}, {1}", row[0], row[1]);

                      item = new ListViewItem(new string[] {row[0].ToString(), row[1].ToString()});
                    lst_data.Items.AddRange(new ListViewItem[] { item });
                }
              
            }
            else
            {
                Console.WriteLine("No data found.");
            }
            
        }
    }
}

Chúc các bạn thành công!

DOWNLOAD SOURCE

 

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[C#] Đọc dữ liệu file data từ Spead Sheet Google Api v4
Đăng bởi: Thảo Meo - Lượt xem: 25173 15:20:31, 26/10/2018DEVEXPRESS   In bài viết

CÁC BÀI CÙNG CHỦ ĐỀ

Đọc tiếp
.