Cách tạo Excel bằng Microsoft Office Interop Excel C#?

Tạo Ứng dụng bảng điều khiển mới bằng cách nhấp vào menu Tệp -> Mới -> Dự án -> Ứng dụng bảng điều khiển của studio trực quan

Đặt tên nó là ExportProductsToExcel

Nếu bạn chỉ muốn chuyển đổi dữ liệu của mình sang CSV, bạn có thể xem Convert DataTable to CSV

Tham chiếu đến Microsoft. Văn phòng. tương tác. Excel

Mở trình khám phá giải pháp và nhấp chuột phải vào Tài liệu tham khảo chọn Thêm tài liệu tham khảo

Từ hộp thoại Thêm tài liệu tham khảo bấm vào. NET, chọn Microsoft. Văn phòng. tương tác. Excel và nhấp vào Ok. Microsoft Office phải được cài đặt trên máy của bạn để sử dụng Microsoft. Văn phòng. thư viện tương tác. Nếu bạn chưa cài đặt, hãy nhấp vào đây để cài đặt Microsoft Office 2010 Primary Interop Assemblies

Chương trình mở. cs của ứng dụng và thêm bên dưới bằng cách sử dụng các câu lệnh

using System.Reflection;
using System.Data.SqlClient;   
using System.Runtime.InteropServices;
using SQL = System.Data;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Excel;

Đọc dữ liệu từ SQL Server

Tạo kết nối bằng Visual Studio Server Explorer tới Northwind. bảng sản phẩm. Bạn có thể xem chi tiết hơn về cơ sở dữ liệu Access SQL Server từ ứng dụng bảng điều khiển

string conString = "your connection string";
StringBuilder query = new StringBuilder();
query.Append("SELECT Categories.CategoryName ");
query.Append(",[ProductID], [ProductName], [SupplierID] ");
query.Append(",[QuantityPerUnit], [UnitPrice], [UnitsInStock] ");
query.Append(",[UnitsOnOrder], [ReorderLevel], [Discontinued] ");
query.Append("FROM [northwind].[dbo].[Products] ");
query.Append("JOIN Categories ON Categories.CategoryID = Products.CategoryID ");
query.Append("ORDER BY Categories.CategoryName ");

SQL.DataTable dtProducts = new SQL.DataTable();
using (SqlConnection cn = new SqlConnection(conString))
{
    using (SqlDataAdapter da = new SqlDataAdapter(query.ToString(), cn))
    {
        da.Fill(dtProducts);
    }
}
    

Tạo đối tượng Excel

Tạo các đối tượng excel của Ứng dụng, Sổ làm việc, Bảng tính sẽ xử lý khả năng tương tác và giao tiếp giữa COM và. mã mạng

Thêm mã bên dưới để tạo các đối tượng cần thiết

Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
            
oXL = new Excel.Application();
oXL.Visible = true;

oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));
oSheet = (Excel._Worksheet)oWB.ActiveSheet;

    

Tạo Category thông minh excel Worksheet

Hướng dẫn này sẽ tạo trang tính cho từng danh mục và sản phẩm sẽ được hiển thị theo danh mục của họ. Chúng tôi cần lấy các danh mục duy nhất từ ​​Bảng dữ liệu sản phẩm

Thêm mã bên dưới để lấy tên danh mục duy nhất, tạo trang tính cho từng danh mục, đặt tên cho danh mục như được đề cập trong DataTable

try
{
    SQL.DataTable dtCategories = 
            dtProducts.DefaultView.ToTable(true, "CategoryName");

    foreach (SQL.DataRow category in dtCategories.Rows)
    {
        oSheet = (Excel._Worksheet)oXL.Worksheets.Add();
        oSheet.Name = category[0].ToString().Replace(" ", "").
            Replace("  ", "").Replace("/", "").
                Replace("\\", "").Replace("*", "");
    }
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);  
}
finally
{   
    Marshal.ReleaseComObject(oWB);
}

    

cho tất cả các chương trình. mã cs nhấp vào cô ấy

Thêm tên cột vào bảng tính excel

Mã bên dưới sẽ đọc tên Cột từ DataTable và thêm nó vào các ô của trang tính Excel. Nó cũng làm cho các tên cột thành Bold và căn chỉnh của nó thành Dọc

Nó tạo mảng chuỗi chứa tên cột và đặt nó thành các ô excel. Điều này sử dụng phương thức get_Range của Worksheet để đặt dữ liệu, phông chữ và căn chỉnh các ô trong phạm vi

string[] colNames = new string[dtProducts.Columns.Count];

int col = 0;

foreach (SQL.DataColumn dc in dtProducts.Columns)
    colNames[col++] = dc.ColumnName;

char lastColumn = (char)(65 + dtProducts.Columns.Count - 1);

oSheet.get_Range("A1", lastColumn + "1").Value2 = colNames;
oSheet.get_Range("A1", lastColumn + "1").Font.Bold = true;
oSheet.get_Range("A1", lastColumn + "1").VerticalAlignment 
            = Excel.XlVAlign.xlVAlignCenter;

    

Thêm dữ liệu DataRows vào Excel

Mã bên dưới sẽ đọc dữ liệu từ Bảng dữ liệu sản phẩm theo Danh mục. Nó tạo mảng DataRow của một danh mục và sau đó xử lý nó thành mảng chuỗi hai chiều

Các giá trị của mảng chuỗi sẽ được đặt thành ô trang tính excel bằng phương thức get_Range

Nếu giá trị cột của ReorderLevel nhỏ hơn UnitsOnOrder thì màu nền của hàng excel tương ứng sẽ được đặt thành Đỏ

Hướng dẫn này giải thích cách đọc tệp Excel trong C# và cách sử dụng thư viện cho các tác vụ hàng ngày như xác thực, chuyển đổi sang cơ sở dữ liệu, lưu dữ liệu từ API Web và sửa đổi công thức trong bảng tính. Bài viết này tham khảo các mẫu mã IronXL, đây là một. Ứng dụng bảng điều khiển NET Core

Đọc và tạo các tệp Excel trong C# và tất cả các tệp khác. NET rất dễ sử dụng thư viện phần mềm IronXL

Nó không yêu cầu cài đặt Excel trên máy chủ của bạn hoặc Interop. IronXL cung cấp API nhanh hơn và trực quan hơn Microsoft. Văn phòng. tương tác. Excel


Tổng quan

Cách đọc tệp Excel trong C#

  1. Tải Thư viện C# để đọc file Excel
  2. Tải và đọc tệp Excel (sổ làm việc)
  3. Tạo sổ làm việc Excel trong CSV hoặc XLSX
  4. Chỉnh sửa giá trị ô trong một dải ô
  5. Xác thực dữ liệu bảng tính
  6. Xuất dữ liệu bằng Entity Framework

Đọc dữ liệu từ tệp Excel bằng IronXL

SắtXL là một. NET hỗ trợ đọc và chỉnh sửa tài liệu Microsoft Excel bằng C#. Hướng dẫn này sẽ hướng dẫn bạn cách sử dụng mã sắc nét C để đọc tệp Excel

  1. Cài đặt Thư viện IronXL Excel. Chúng tôi có thể thực hiện việc này bằng gói NuGet của mình hoặc bằng cách tải xuống. Net Excel DLL
  2. Sử dụng Sổ làm việc. Phương pháp tải để đọc bất kỳ tài liệu XLS, XLSX hoặc CSV nào
  3. Nhận các giá trị ô bằng cú pháp trực quan.
     PM > Install-Package IronXL.Excel
    7

SắtXL bao gồm

  • Hỗ trợ sản phẩm chuyên dụng từ chúng tôi. kỹ sư NET
  • Cài đặt dễ dàng qua Microsoft Visual Studio
  • Dùng thử miễn phí 30 ngày để phát triển. Giấy phép từ $749

Chúng ta sẽ thấy việc đọc tệp Excel bằng C# hoặc VB dễ dàng như thế nào. NET bằng thư viện IronXL. Các mẫu chứa ba bảng Excel

Cách tạo Excel bằng Microsoft Office Interop Excel C#?

Đọc tệp XLS hoặc XLSX. Mã nhanh

Trong ví dụ này, chúng ta có thể thấy cách đọc tệp excel hiệu quả mà không cần Interop trong C#. Hoạt động nâng cao cuối cùng cho thấy khả năng tương thích Linq và toán học phạm vi tổng hợp

/**
Read XLS or XLSX File
anchor-read-an-xls-or-xlsx-file
**/
using IronXL;
using System.Linq;

//Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
WorkBook workbook = WorkBook.Load("test.xlsx");
WorkSheet sheet = workbook.WorkSheets.First();
//Select cells easily in Excel notation and return the calculated value
int cellValue = sheet["A2"].IntValue;
// Read from Ranges of cells elegantly.
foreach (var cell in sheet["A2:A10"])
{
    Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}

///Advanced Operations

//Calculate aggregate values such as Min, Max and Sum
decimal sum = sheet["A2:A10"].Sum();
//Linq compatible
decimal max = sheet["A2:A10"].Max(c => c.DecimalValue);

/**
Read XLS or XLSX File
anchor-read-an-xls-or-xlsx-file
**/
using IronXL;
using System.Linq;

//Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
WorkBook workbook = WorkBook.Load("test.xlsx");
WorkSheet sheet = workbook.WorkSheets.First();
//Select cells easily in Excel notation and return the calculated value
int cellValue = sheet["A2"].IntValue;
// Read from Ranges of cells elegantly.
foreach (var cell in sheet["A2:A10"])
{
    Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}

///Advanced Operations

//Calculate aggregate values such as Min, Max and Sum
decimal sum = sheet["A2:A10"].Sum();
//Linq compatible
decimal max = sheet["A2:A10"].Max(c => c.DecimalValue);
'''
'''Read XLS or XLSX File
'''anchor-read-an-xls-or-xlsx-file
'''*
Imports IronXL
Imports System.Linq

'Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
Private workbook As WorkBook = WorkBook.Load("test.xlsx")
Private sheet As WorkSheet = workbook.WorkSheets.First()
'Select cells easily in Excel notation and return the calculated value
Private cellValue As Integer = sheet("A2").IntValue
' Read from Ranges of cells elegantly.
For Each cell In sheet("A2:A10")
	Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text)
Next cell

'''Advanced Operations

'Calculate aggregate values such as Min, Max and Sum
Dim sum As Decimal = sheet("A2:A10").Sum()
'Linq compatible
Dim max As Decimal = sheet("A2:A10").Max(Function(c) c.DecimalValue)

VB   C#


Bước 1

1. Tải xuống Thư viện IronXL C# MIỄN PHÍ

Cách tạo Excel bằng Microsoft Office Interop Excel C#?

Tải xuống DLL

Tải xuống DLL

Cài đặt thủ công vào dự án của bạn

hoặc là

Cách tạo Excel bằng Microsoft Office Interop Excel C#?

Cài đặt bằng NuGet

Install-Package IronXL.Excel

nuget. org/gói/IronXL. Excel/

Điều đầu tiên chúng ta cần làm là cài đặt IronXL. Thư viện Excel, thêm chức năng Excel vào. Nền tảng NET

Cài đặt IronXL. Excel, đạt được dễ dàng nhất bằng cách sử dụng gói NuGet của chúng tôi, mặc dù bạn cũng có thể chọn cài đặt DLL theo cách thủ công vào dự án của mình hoặc vào bộ đệm lắp ráp chung của bạn

Cài đặt Gói NuGet IronXL

  1. Trong Visual Studio, nhấp chuột phải vào dự án chọn "Quản lý gói NuGet. "
  2. Tìm kiếm IronXL. Gói và cài đặt Excel

    Cách tạo Excel bằng Microsoft Office Interop Excel C#?


Một cách khác để cài đặt là

  1. Nhập Bảng điều khiển quản lý gói
  2. Nhập > Gói cài đặt IronXL. Excel
 PM > Install-Package IronXL.Excel


Ngoài ra, bạn có thể xem gói trên trang NuGet tại đây

Cài đặt tải xuống trực tiếp

Ngoài ra, chúng ta có thể bắt đầu bằng cách tải xuống IronXL. NET Excel DLL và cài đặt thủ công vào Visual Studio


Làm thế nào để hướng dẫn

2. Tải một WorkBook

Lớp

 PM > Install-Package IronXL.Excel
8 đại diện cho một trang tính Excel. Để mở một File Excel bằng C#, chúng ta sử dụng WorkBook. Tải và chỉ định đường dẫn của tệp Excel (. xlsx)

/**
Load WorkBook
anchor-load-a-workbook
**/
var workbook = WorkBook.Load(@"Spreadsheets\\GDP.xlsx");

/**
Load WorkBook
anchor-load-a-workbook
**/
var workbook = WorkBook.Load(@"Spreadsheets\\GDP.xlsx");
'''
'''Load WorkBook
'''anchor-load-a-workbook
'''*
Dim workbook = WorkBook.Load("Spreadsheets\\GDP.xlsx")

VB   C#

Vật mẫu. ExcelToDBBộ xử lý

Mỗi WorkBook có thể có nhiều đối tượng

 PM > Install-Package IronXL.Excel
9. Chúng đại diện cho các trang tính trong tài liệu Excel. Nếu trang tính chứa các trang tính, hãy truy xuất chúng theo tên
/**
Load WorkBook
anchor-load-a-workbook
**/
var workbook = WorkBook.Load(@"Spreadsheets\\GDP.xlsx");
0

var worksheet = workbook.GetWorkSheet("GDPByCountry");

var worksheet = workbook.GetWorkSheet("GDPByCountry");
/**
Read XLS or XLSX File
anchor-read-an-xls-or-xlsx-file
**/
using IronXL;
using System.Linq;

//Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
WorkBook workbook = WorkBook.Load("test.xlsx");
WorkSheet sheet = workbook.WorkSheets.First();
//Select cells easily in Excel notation and return the calculated value
int cellValue = sheet["A2"].IntValue;
// Read from Ranges of cells elegantly.
foreach (var cell in sheet["A2:A10"])
{
    Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}

///Advanced Operations

//Calculate aggregate values such as Min, Max and Sum
decimal sum = sheet["A2:A10"].Sum();
//Linq compatible
decimal max = sheet["A2:A10"].Max(c => c.DecimalValue);
0

VB   C#

Vật mẫu. ExcelToDB


3. Tạo Sổ làm việc

Để tạo một Sổ làm việc mới trong bộ nhớ, hãy tạo một Sổ làm việc mới với loại trang tính

/**
Read XLS or XLSX File
anchor-read-an-xls-or-xlsx-file
**/
using IronXL;
using System.Linq;

//Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
WorkBook workbook = WorkBook.Load("test.xlsx");
WorkSheet sheet = workbook.WorkSheets.First();
//Select cells easily in Excel notation and return the calculated value
int cellValue = sheet["A2"].IntValue;
// Read from Ranges of cells elegantly.
foreach (var cell in sheet["A2:A10"])
{
    Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}

///Advanced Operations

//Calculate aggregate values such as Min, Max and Sum
decimal sum = sheet["A2:A10"].Sum();
//Linq compatible
decimal max = sheet["A2:A10"].Max(c => c.DecimalValue);
1

/**
Read XLS or XLSX File
anchor-read-an-xls-or-xlsx-file
**/
using IronXL;
using System.Linq;

//Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
WorkBook workbook = WorkBook.Load("test.xlsx");
WorkSheet sheet = workbook.WorkSheets.First();
//Select cells easily in Excel notation and return the calculated value
int cellValue = sheet["A2"].IntValue;
// Read from Ranges of cells elegantly.
foreach (var cell in sheet["A2:A10"])
{
    Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}

///Advanced Operations

//Calculate aggregate values such as Min, Max and Sum
decimal sum = sheet["A2:A10"].Sum();
//Linq compatible
decimal max = sheet["A2:A10"].Max(c => c.DecimalValue);
1
/**
Read XLS or XLSX File
anchor-read-an-xls-or-xlsx-file
**/
using IronXL;
using System.Linq;

//Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
WorkBook workbook = WorkBook.Load("test.xlsx");
WorkSheet sheet = workbook.WorkSheets.First();
//Select cells easily in Excel notation and return the calculated value
int cellValue = sheet["A2"].IntValue;
// Read from Ranges of cells elegantly.
foreach (var cell in sheet["A2:A10"])
{
    Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}

///Advanced Operations

//Calculate aggregate values such as Min, Max and Sum
decimal sum = sheet["A2:A10"].Sum();
//Linq compatible
decimal max = sheet["A2:A10"].Max(c => c.DecimalValue);
3

VB   C#

Vật mẫu. Bộ xử lý ApiToExcel

Ghi chú. Sử dụng ExcelFileFormat. XLS dành cho kế thừa cho bảng tính Microsoft Excel (95 trở về trước)


4. Tạo một bảng tính

Mỗi "WorkBook" có thể có nhiều WorkSheet. "WorkSheet" là một trang tính dữ liệu, trong khi WorkBook đại diện cho một tập hợp các WorkSheet. Đây là giao diện của một sổ làm việc có hai trang tính trong Excel

Cách tạo Excel bằng Microsoft Office Interop Excel C#?

Để tạo một WorkSheet mới, hãy gọi

/**
Load WorkBook
anchor-load-a-workbook
**/
var workbook = WorkBook.Load(@"Spreadsheets\\GDP.xlsx");
1 và chuyển tên của trang tính

/**
Read XLS or XLSX File
anchor-read-an-xls-or-xlsx-file
**/
using IronXL;
using System.Linq;

//Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
WorkBook workbook = WorkBook.Load("test.xlsx");
WorkSheet sheet = workbook.WorkSheets.First();
//Select cells easily in Excel notation and return the calculated value
int cellValue = sheet["A2"].IntValue;
// Read from Ranges of cells elegantly.
foreach (var cell in sheet["A2:A10"])
{
    Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}

///Advanced Operations

//Calculate aggregate values such as Min, Max and Sum
decimal sum = sheet["A2:A10"].Sum();
//Linq compatible
decimal max = sheet["A2:A10"].Max(c => c.DecimalValue);
4

/**
Read XLS or XLSX File
anchor-read-an-xls-or-xlsx-file
**/
using IronXL;
using System.Linq;

//Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
WorkBook workbook = WorkBook.Load("test.xlsx");
WorkSheet sheet = workbook.WorkSheets.First();
//Select cells easily in Excel notation and return the calculated value
int cellValue = sheet["A2"].IntValue;
// Read from Ranges of cells elegantly.
foreach (var cell in sheet["A2:A10"])
{
    Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}

///Advanced Operations

//Calculate aggregate values such as Min, Max and Sum
decimal sum = sheet["A2:A10"].Sum();
//Linq compatible
decimal max = sheet["A2:A10"].Max(c => c.DecimalValue);
4_______6_______6

VB   C#


5. Nhận phạm vi ô

Lớp "Phạm vi" đại diện cho một tập hợp hai chiều của các đối tượng "Ô". Nó đại diện cho một phạm vi ô Excel theo nghĩa đen. Lấy phạm vi bằng cách sử dụng bộ chỉ mục chuỗi trên đối tượng WorkSheet

Văn bản đối số là tọa độ của một ô (e. g. "A1") hoặc một dãy ô từ trái sang phải từ trên xuống dưới (e. g. "B2. E5"). Cũng có thể gọi

/**
Load WorkBook
anchor-load-a-workbook
**/
var workbook = WorkBook.Load(@"Spreadsheets\\GDP.xlsx");
2 trên WorkSheet

/**
Read XLS or XLSX File
anchor-read-an-xls-or-xlsx-file
**/
using IronXL;
using System.Linq;

//Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
WorkBook workbook = WorkBook.Load("test.xlsx");
WorkSheet sheet = workbook.WorkSheets.First();
//Select cells easily in Excel notation and return the calculated value
int cellValue = sheet["A2"].IntValue;
// Read from Ranges of cells elegantly.
foreach (var cell in sheet["A2:A10"])
{
    Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}

///Advanced Operations

//Calculate aggregate values such as Min, Max and Sum
decimal sum = sheet["A2:A10"].Sum();
//Linq compatible
decimal max = sheet["A2:A10"].Max(c => c.DecimalValue);
7

/**
Read XLS or XLSX File
anchor-read-an-xls-or-xlsx-file
**/
using IronXL;
using System.Linq;

//Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
WorkBook workbook = WorkBook.Load("test.xlsx");
WorkSheet sheet = workbook.WorkSheets.First();
//Select cells easily in Excel notation and return the calculated value
int cellValue = sheet["A2"].IntValue;
// Read from Ranges of cells elegantly.
foreach (var cell in sheet["A2:A10"])
{
    Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}

///Advanced Operations

//Calculate aggregate values such as Min, Max and Sum
decimal sum = sheet["A2:A10"].Sum();
//Linq compatible
decimal max = sheet["A2:A10"].Max(c => c.DecimalValue);
7
/**
Read XLS or XLSX File
anchor-read-an-xls-or-xlsx-file
**/
using IronXL;
using System.Linq;

//Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
WorkBook workbook = WorkBook.Load("test.xlsx");
WorkSheet sheet = workbook.WorkSheets.First();
//Select cells easily in Excel notation and return the calculated value
int cellValue = sheet["A2"].IntValue;
// Read from Ranges of cells elegantly.
foreach (var cell in sheet["A2:A10"])
{
    Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}

///Advanced Operations

//Calculate aggregate values such as Min, Max and Sum
decimal sum = sheet["A2:A10"].Sum();
//Linq compatible
decimal max = sheet["A2:A10"].Max(c => c.DecimalValue);
9

VB   C#

Vật mẫu. Xác nhận dữ liệu


6. Chỉnh sửa giá trị ô trong phạm vi

Có một số cách để đọc hoặc chỉnh sửa giá trị của các ô trong Phạm vi. Nếu đã biết số đếm, hãy sử dụng vòng lặp For

'''
'''Read XLS or XLSX File
'''anchor-read-an-xls-or-xlsx-file
'''*
Imports IronXL
Imports System.Linq

'Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
Private workbook As WorkBook = WorkBook.Load("test.xlsx")
Private sheet As WorkSheet = workbook.WorkSheets.First()
'Select cells easily in Excel notation and return the calculated value
Private cellValue As Integer = sheet("A2").IntValue
' Read from Ranges of cells elegantly.
For Each cell In sheet("A2:A10")
	Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text)
Next cell

'''Advanced Operations

'Calculate aggregate values such as Min, Max and Sum
Dim sum As Decimal = sheet("A2:A10").Sum()
'Linq compatible
Dim max As Decimal = sheet("A2:A10").Max(Function(c) c.DecimalValue)
0

'''
'''Read XLS or XLSX File
'''anchor-read-an-xls-or-xlsx-file
'''*
Imports IronXL
Imports System.Linq

'Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
Private workbook As WorkBook = WorkBook.Load("test.xlsx")
Private sheet As WorkSheet = workbook.WorkSheets.First()
'Select cells easily in Excel notation and return the calculated value
Private cellValue As Integer = sheet("A2").IntValue
' Read from Ranges of cells elegantly.
For Each cell In sheet("A2:A10")
	Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text)
Next cell

'''Advanced Operations

'Calculate aggregate values such as Min, Max and Sum
Dim sum As Decimal = sheet("A2:A10").Sum()
'Linq compatible
Dim max As Decimal = sheet("A2:A10").Max(Function(c) c.DecimalValue)
0
'''
'''Read XLS or XLSX File
'''anchor-read-an-xls-or-xlsx-file
'''*
Imports IronXL
Imports System.Linq

'Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
Private workbook As WorkBook = WorkBook.Load("test.xlsx")
Private sheet As WorkSheet = workbook.WorkSheets.First()
'Select cells easily in Excel notation and return the calculated value
Private cellValue As Integer = sheet("A2").IntValue
' Read from Ranges of cells elegantly.
For Each cell In sheet("A2:A10")
	Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text)
Next cell

'''Advanced Operations

'Calculate aggregate values such as Min, Max and Sum
Dim sum As Decimal = sheet("A2:A10").Sum()
'Linq compatible
Dim max As Decimal = sheet("A2:A10").Max(Function(c) c.DecimalValue)
2

VB   C#

Vật mẫu. Xác nhận dữ liệu


7. Xác thực dữ liệu bảng tính

Sử dụng IronXL để xác thực bảng dữ liệu. Mẫu DataValidation sử dụng

/**
Load WorkBook
anchor-load-a-workbook
**/
var workbook = WorkBook.Load(@"Spreadsheets\\GDP.xlsx");
3 để xác thực số điện thoại và sử dụng API C# tiêu chuẩn để xác thực địa chỉ email và ngày tháng

'''
'''Read XLS or XLSX File
'''anchor-read-an-xls-or-xlsx-file
'''*
Imports IronXL
Imports System.Linq

'Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
Private workbook As WorkBook = WorkBook.Load("test.xlsx")
Private sheet As WorkSheet = workbook.WorkSheets.First()
'Select cells easily in Excel notation and return the calculated value
Private cellValue As Integer = sheet("A2").IntValue
' Read from Ranges of cells elegantly.
For Each cell In sheet("A2:A10")
	Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text)
Next cell

'''Advanced Operations

'Calculate aggregate values such as Min, Max and Sum
Dim sum As Decimal = sheet("A2:A10").Sum()
'Linq compatible
Dim max As Decimal = sheet("A2:A10").Max(Function(c) c.DecimalValue)
3

'''
'''Read XLS or XLSX File
'''anchor-read-an-xls-or-xlsx-file
'''*
Imports IronXL
Imports System.Linq

'Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
Private workbook As WorkBook = WorkBook.Load("test.xlsx")
Private sheet As WorkSheet = workbook.WorkSheets.First()
'Select cells easily in Excel notation and return the calculated value
Private cellValue As Integer = sheet("A2").IntValue
' Read from Ranges of cells elegantly.
For Each cell In sheet("A2:A10")
	Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text)
Next cell

'''Advanced Operations

'Calculate aggregate values such as Min, Max and Sum
Dim sum As Decimal = sheet("A2:A10").Sum()
'Linq compatible
Dim max As Decimal = sheet("A2:A10").Max(Function(c) c.DecimalValue)
3_______8_______5

VB   C#

Đoạn mã trên lặp qua từng hàng trong bảng tính và lấy các ô dưới dạng danh sách. Mỗi phương thức xác thực sẽ kiểm tra giá trị của một ô và trả về thông báo lỗi nếu giá trị không hợp lệ

Mã này tạo một trang tính mới, chỉ định tiêu đề và xuất kết quả thông báo lỗi để có nhật ký dữ liệu không hợp lệ

'''
'''Read XLS or XLSX File
'''anchor-read-an-xls-or-xlsx-file
'''*
Imports IronXL
Imports System.Linq

'Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
Private workbook As WorkBook = WorkBook.Load("test.xlsx")
Private sheet As WorkSheet = workbook.WorkSheets.First()
'Select cells easily in Excel notation and return the calculated value
Private cellValue As Integer = sheet("A2").IntValue
' Read from Ranges of cells elegantly.
For Each cell In sheet("A2:A10")
	Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text)
Next cell

'''Advanced Operations

'Calculate aggregate values such as Min, Max and Sum
Dim sum As Decimal = sheet("A2:A10").Sum()
'Linq compatible
Dim max As Decimal = sheet("A2:A10").Max(Function(c) c.DecimalValue)
6

'''
'''Read XLS or XLSX File
'''anchor-read-an-xls-or-xlsx-file
'''*
Imports IronXL
Imports System.Linq

'Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
Private workbook As WorkBook = WorkBook.Load("test.xlsx")
Private sheet As WorkSheet = workbook.WorkSheets.First()
'Select cells easily in Excel notation and return the calculated value
Private cellValue As Integer = sheet("A2").IntValue
' Read from Ranges of cells elegantly.
For Each cell In sheet("A2:A10")
	Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text)
Next cell

'''Advanced Operations

'Calculate aggregate values such as Min, Max and Sum
Dim sum As Decimal = sheet("A2:A10").Sum()
'Linq compatible
Dim max As Decimal = sheet("A2:A10").Max(Function(c) c.DecimalValue)
6
'''
'''Read XLS or XLSX File
'''anchor-read-an-xls-or-xlsx-file
'''*
Imports IronXL
Imports System.Linq

'Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
Private workbook As WorkBook = WorkBook.Load("test.xlsx")
Private sheet As WorkSheet = workbook.WorkSheets.First()
'Select cells easily in Excel notation and return the calculated value
Private cellValue As Integer = sheet("A2").IntValue
' Read from Ranges of cells elegantly.
For Each cell In sheet("A2:A10")
	Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text)
Next cell

'''Advanced Operations

'Calculate aggregate values such as Min, Max and Sum
Dim sum As Decimal = sheet("A2:A10").Sum()
'Linq compatible
Dim max As Decimal = sheet("A2:A10").Max(Function(c) c.DecimalValue)
8

VB   C#


8. Xuất dữ liệu bằng Entity Framework

Sử dụng IronXL để xuất dữ liệu sang cơ sở dữ liệu hoặc chuyển đổi bảng tính Excel sang cơ sở dữ liệu. Mẫu

/**
Load WorkBook
anchor-load-a-workbook
**/
var workbook = WorkBook.Load(@"Spreadsheets\\GDP.xlsx");
4 đọc bảng tính có GDP theo quốc gia rồi xuất dữ liệu đó sang SQLite

Nó sử dụng EntityFramework để xây dựng cơ sở dữ liệu và sau đó xuất dữ liệu theo từng dòng

Thêm các gói NuGet của SQLite Entity Framework

Cách tạo Excel bằng Microsoft Office Interop Excel C#?

EntityFramework cho phép bạn tạo một đối tượng mô hình có thể xuất dữ liệu vào cơ sở dữ liệu

'''
'''Read XLS or XLSX File
'''anchor-read-an-xls-or-xlsx-file
'''*
Imports IronXL
Imports System.Linq

'Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
Private workbook As WorkBook = WorkBook.Load("test.xlsx")
Private sheet As WorkSheet = workbook.WorkSheets.First()
'Select cells easily in Excel notation and return the calculated value
Private cellValue As Integer = sheet("A2").IntValue
' Read from Ranges of cells elegantly.
For Each cell In sheet("A2:A10")
	Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text)
Next cell

'''Advanced Operations

'Calculate aggregate values such as Min, Max and Sum
Dim sum As Decimal = sheet("A2:A10").Sum()
'Linq compatible
Dim max As Decimal = sheet("A2:A10").Max(Function(c) c.DecimalValue)
9

'''
'''Read XLS or XLSX File
'''anchor-read-an-xls-or-xlsx-file
'''*
Imports IronXL
Imports System.Linq

'Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
Private workbook As WorkBook = WorkBook.Load("test.xlsx")
Private sheet As WorkSheet = workbook.WorkSheets.First()
'Select cells easily in Excel notation and return the calculated value
Private cellValue As Integer = sheet("A2").IntValue
' Read from Ranges of cells elegantly.
For Each cell In sheet("A2:A10")
	Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text)
Next cell

'''Advanced Operations

'Calculate aggregate values such as Min, Max and Sum
Dim sum As Decimal = sheet("A2:A10").Sum()
'Linq compatible
Dim max As Decimal = sheet("A2:A10").Max(Function(c) c.DecimalValue)
9
Install-Package IronXL.Excel
1

VB   C#

Để sử dụng cơ sở dữ liệu khác, hãy cài đặt gói NuGet tương ứng và tìm gói tương đương với

/**
Load WorkBook
anchor-load-a-workbook
**/
var workbook = WorkBook.Load(@"Spreadsheets\\GDP.xlsx");
5

Install-Package IronXL.Excel
2

Install-Package IronXL.Excel
2
Install-Package IronXL.Excel
4

VB   C#

Tạo một

/**
Load WorkBook
anchor-load-a-workbook
**/
var workbook = WorkBook.Load(@"Spreadsheets\\GDP.xlsx");
6, lặp qua phạm vi để tạo từng bản ghi, sau đó
/**
Load WorkBook
anchor-load-a-workbook
**/
var workbook = WorkBook.Load(@"Spreadsheets\\GDP.xlsx");
7 để chuyển giao dữ liệu vào cơ sở dữ liệu

Install-Package IronXL.Excel
5

Install-Package IronXL.Excel
5
Install-Package IronXL.Excel
7

VB   C#

Vật mẫu. ExcelToDB


9. Thêm công thức vào bảng tính

Đặt công thức của

/**
Load WorkBook
anchor-load-a-workbook
**/
var workbook = WorkBook.Load(@"Spreadsheets\\GDP.xlsx");
8 với thuộc tính
/**
Load WorkBook
anchor-load-a-workbook
**/
var workbook = WorkBook.Load(@"Spreadsheets\\GDP.xlsx");
9

Mã bên dưới lặp qua từng trạng thái và đặt tổng tỷ lệ phần trăm vào cột C

Install-Package IronXL.Excel
8

Install-Package IronXL.Excel
8
 PM > Install-Package IronXL.Excel
0

VB   C#

Vật mẫu. AddFormulaeBộ xử lý


10. Tải dữ liệu từ API xuống bảng tính

Cuộc gọi sau thực hiện cuộc gọi REST với RestClient. Net. Nó tải xuống JSON và chuyển đổi nó thành một "Danh sách" thuộc loại

/**
Load WorkBook
anchor-load-a-workbook
**/
var workbook = WorkBook.Load(@"Spreadsheets\\GDP.xlsx");
0. Sau đó, có thể dễ dàng lặp lại qua từng quốc gia và lưu dữ liệu từ API REST vào bảng tính Excel

 PM > Install-Package IronXL.Excel
1

 PM > Install-Package IronXL.Excel
1_______5_______3

VB   C#

Vật mẫu. ApiToExcel

Đây là dữ liệu API JSON trông như thế nào

Cách tạo Excel bằng Microsoft Office Interop Excel C#?

Đoạn mã sau lặp qua các quốc gia và đặt Tên, Dân số, Vùng, Mã số và 3 Ngôn ngữ hàng đầu trong bảng tính

 PM > Install-Package IronXL.Excel
4

 PM > Install-Package IronXL.Excel
4_______5_______6

VB   C#


Tài nguyên và tham chiếu đối tượng

Bạn cũng có thể tìm thấy tài liệu về lớp IronXL trong Tham chiếu đối tượng có giá trị lớn

Ngoài ra, còn có các hướng dẫn khác có thể làm sáng tỏ các khía cạnh khác của IronXL. Excel bao gồm Tạo, Mở, Viết, Chỉnh sửa, Lưu và Xuất các tệp XLS, XLSX và CSV mà không cần sử dụng Excel Interop

Tóm lược

sắtXL. Excel chỉ có một mình. NET để đọc nhiều định dạng bảng tính. Nó không yêu cầu cài đặt Microsoft Excel và không phụ thuộc vào Interop


Hướng dẫn Truy cập nhanh

Tải xuống Hướng dẫn này dưới dạng Mã nguồn C#

Mã nguồn C# cho Excel đầy đủ miễn phí cho hướng dẫn này có sẵn để tải xuống dưới dạng tệp dự án Visual Studio 2017 được nén

Tải xuống

Khám phá Hướng dẫn này trên GitHub

Mã nguồn cho dự án này có sẵn trong C# và VB. NET trên GitHub

Sử dụng mã này như một cách dễ dàng để thiết lập và chạy chỉ trong vài phút. Dự án được lưu dưới dạng dự án Microsoft Visual Studio 2017, nhưng tương thích với bất kỳ. NET IDE

Cách đọc tệp Excel trong C# trên GitHub

Xem tham chiếu API

Khám phá Tài liệu tham khảo API cho IronXL, phác thảo chi tiết về tất cả các tính năng, không gian tên, lớp, trường phương thức và enum của IronXL

Xem tham chiếu API

Cách tạo Excel bằng Microsoft Office Interop Excel C#?

Christian Findlay

Trưởng nhóm phát triển phần mềm

Christian xây dựng phần mềm cho ngành y tế và lãnh đạo một nhóm. Christian có nhiều năm kinh nghiệm tích hợp với các loại hệ thống. IronXL cho phép Christian nhập và thao tác dữ liệu từ các nguồn khác nhau để tự động hóa các tác vụ lặp đi lặp lại và xác thực dữ liệu đầu vào từ các nguồn của bên thứ 3

Làm cách nào để tạo Excel bằng C#?

Cách tạo tệp Excel trong C# .
Tải xuống Thư viện C# để tạo tệp Excel và CSV
Tạo một ASP. Ứng dụng web dự án NET
Tạo Sổ làm việc Excel với Thư viện C#
Đặt giá trị ô trong trang tính Excel theo cách thủ công
Áp dụng định dạng và đặt màu nền của ô
Sử dụng công thức trong ô

Ứng dụng Microsoft Office Interop Excel là gì?

Microsoft Office Interop (Tự động hóa Excel) là một tùy chọn khi tạo/đọc các tệp Excel (XLS, XLSX, CSV) từ C# hoặc VB. NET , nhưng nó có nhiều nhược điểm.

Làm cách nào để tạo Excel bằng ClosedXML C#?

Quảng cáo Sắp xếp C# Excel . Excel; . var wbook = new XLWorkbook(); var ws = wbook. Trang tính. Add("Sheet1"); . .