c# read excel .xlsx

ตอบกระทู้

รูปแสดงอารมณ์
:icon_plusone: :like: :plusone: :gfb: :-D :) :( :-o 8O :? 8) :lol: :x :P :oops: :cry: :evil: :twisted: :roll: :wink: :!: :?: :idea: :arrow: :| :mrgreen: :angry: :baa: :biggrin:
รูปแสดงอารมณ์อื่นๆ

BBCode เปิด
[img] เปิด
[url] เปิด
[Smile icon] เปิด

กระทู้แนะนำ
   

มุมมองที่ขยายได้ กระทู้แนะนำ: c# read excel .xlsx

c# read excel .xlsx

โดย jataz2 » 14/07/2020 2:50 pm

lib ที่ใช้อ่าน excel คือ SpreadsheetLight
เงื่อนไขอ่านไฟล์ excel .xlsx ได้ ( แต่ .xls อ่านข้อมูลไม่ได้นะ)

ตัวอย่างการนำไปใช้คือก็เช่น กด browse ไฟล์ excel จากนั้น save ไฟล์ไว้ตามพาธ แล้วไปอ่านข้อมูล excel นั้นมาทำงานต่อไป

.GetCellValueAsString ให้ผลลัพท์ออกมาเป็น string
.GetCellValueAsDecimal ให้ผลลัพท์ออกมาเป็น decimal กรณี value ใน excel เป็น 123ก00 จะได้ค่า 0 เพราะมีอักษรปนมาใน value

ที่จริง SpreadsheetLight สามารถ สร้างเอกสาร .xlsx ได้อีกด้วยครับ ทำได้อีกหลายอย่าง

โค้ด: เลือกทั้งหมด

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;
using System.Data;
using System.Configuration;
using System.Text.RegularExpressions;

using SpreadsheetLight;

class Program
{
	static void Main(string[] args)
	{
     	    try
            {
                var memStream = new MemoryStream();

                using (var fileStream = new System.IO.FileStream("D:\covid_data_20190714.xlsx", System.IO.FileMode.Open))
                {
                    fileStream.CopyTo(memStream);
                    memStream.Seek(0, SeekOrigin.Begin);
                }

                using (SLDocument sheet1 = new SLDocument(memStream, "Sheet1"))
                {
                    SLWorksheetStatistics sheetStatistic = sheet1.GetWorksheetStatistics();

                    //ไม่เอาแถว header เอาเฉพาะแถวที่เป็น data
                    //ไม่เอา data แถวที่เป็นผลรวม
                 
                    for (int i = 2; i <= sheetStatistic.EndRowIndex; i++)
                    {
                        if (sheet1.HasCellValue("U" + i) || sheet1.HasCellValue("T" + i) || sheet1.HasCellValue("M" + i) || sheet1.HasCellValue("E" + i))
                        {
                            if ( sheet1.GetCellValueAsString("O" + i).ToString() != "00000000" 
                                && sheet1.GetCellValueAsString("O" + i).ToString() != "0"
                                && sheet1.GetCellValueAsString("O" + i).ToString() != string.Empty) //กรองเอาเฉพาะรายการที่มีเลข ID
                            {
                                string A = sheet1.GetCellValueAsString("U" + i).ToString();
                                string B = sheet1.GetCellValueAsDecimal("M" + i).ToString();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
	}
}
อ่านเพิ่มเติมได้ที่ https://spreadsheetlight.com/sample-code/
แนบไฟล์
SpreadsheetLight.zip
(486.24 KiB) ดาวน์โหลดแล้ว 171 ครั้ง

ข้างบน