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/