Hướng dẫn how read excel file in c# using microsoft office interop excel? - cách đọc tệp excel trong c# bằng microsoft office interop excel?

Vì vậy, có vẻ như giảng viên đã bao gồm tệp .xlsx như là phương tiện để hiển thị ví dụ về tệp được phân định tab. Đây là hoàn thành:

#include "stdafx.h"
#include 
#include "string.h"

void printService(char *type, char *reg, char serviceType, char *month);

void main()
{ 
    char months[12][12] = {"January","February","March","April","May","June","July","August","September","October","November","December"};
    char line[201];
    char type[41], reg[41];
    char service[12];
    int i;

    FILE *ptr;  

    /*
    ptr = fopen( "c:\\path\\to\\file.txt", "r" );

   if (ptr == NULL ) 
   {
      printf( "File could not be opened\n" );
   } 
   else 
   { 
        puts("File Contents");
        while(!feof(ptr))
        {
            fgets(line,200,ptr);
            puts(line);
        }

      fclose( ptr ); 
   } 
   */

   ptr = fopen( "c:\\path\\to\\file.txt", "r" );

   if (ptr == NULL ) 
   {
      printf( "File could not be opened\n" );
   } 
   else 
   { 
            fgets(line,200,ptr);
            fgets(line,200,ptr);
            while(strcmp(type,"END"))
            {
                type[0] = '\0';
                fscanf(ptr, "%s\t%s\t%c\t%c\t%c\t%c\t%c\t%c\t%c\t%c\t%c\t%c\t%c\t%c\n",type,reg,&service[0],&service[1],&service[2],&service[3],
                &service[4],&service[5],&service[6],&service[7],&service[8],&service[9],&service[10],&service[11]);

                if(strcmp(type,"END"))
                {
                for(i=0;i<12;i++)
                {
                    printService(type,reg,service[i], months[i]);
                }
                }
            }
        }

      fclose( ptr ); 

   } 

void printService(char *type, char *reg,char serviceType, char *month)
{
    char service[41];

    if(serviceType != '-')
    {
        if (serviceType == 'S') strcpy(service,"Service Due");
        if (serviceType == 'I') strcpy(service,"Inspection Service Due");
        if (serviceType == 'C') strcpy(service,"Commercial Vehicle Test Due");
        if (serviceType == 'T') strcpy(service,"Two-year Tacho Check Due");

        printf("%s registration %s, in %s has %s \n",type, reg,month, service);
    }

}

Điều này có vẻ tốt với các bạn không? Có bất kỳ cải tiến hiệu quả được đề xuất?

.NET 4+ cho phép C# đọc và thao tác các tệp Microsoft Excel, cho các máy tính đã cài đặt Excel (nếu bạn chưa cài đặt Excel, xem NPOI).

Đầu tiên, thêm tham chiếu vào thư viện đối tượng Microsoft Excel XX.x, nằm trong tab COM của trình quản lý tham chiếu. Tôi đã cho điều này sử dụng bí danh của Excel.

using Excel = Microsoft.Office.Interop.Excel;       //Microsoft Excel 14 object in references-> COM tab

Tiếp theo, bạn sẽ cần tạo tài liệu tham khảo cho từng đối tượng COM được truy cập. Mỗi tài liệu tham khảo phải được giữ để thoát khỏi ứng dụng một cách hiệu quả khi hoàn thành.

//Create COM Objects. Create a COM object for everything that is referenced
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"sandbox_test.xlsx");
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;

Sau đó, bạn có thể đọc từ tờ, hãy nhớ rằng việc lập chỉ mục trong Excel không dựa trên 0. Điều này chỉ đọc các ô và in lại chúng giống như trong tập tin.

//iterate over the rows and columns and print to the console as it appears in the file
//excel is not zero based!!
for (int i = 1; i <= rowCount; i++)
{
    for (int j = 1; j <= colCount; j++)
    {
        //new line
        if (j == 1)
            Console.Write("\r\n");

        //write the value to the console
        if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null)
            Console.Write(xlRange.Cells[i, j].Value2.ToString() + "\t");

        //add useful things here!   
    }
}

Cuối cùng, các tài liệu tham khảo về bộ nhớ không được quản lý phải được phát hành. Nếu điều này không được thực hiện đúng, thì sẽ có các quy trình kéo dài sẽ giữ truy cập tệp ghi vào sổ làm việc Excel của bạn.

//cleanup
GC.Collect();
GC.WaitForPendingFinalizers();

//rule of thumb for releasing com objects:
//  never use two dots, all COM objects must be referenced and released individually
//  ex: [somthing].[something].[something] is bad

//release com objects to fully kill excel process from running in the background
Marshal.ReleaseComObject(xlRange);
Marshal.ReleaseComObject(xlWorksheet);

//close and release
xlWorkbook.Close();
Marshal.ReleaseComObject(xlWorkbook);

//quit and release
xlApp.Quit();
Marshal.ReleaseComObject(xlApp);

Đọc thêm:

Stackoverflow

Interop sắp xếp

Excel và C#

Mã đầy đủ:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;           
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;       //microsoft Excel 14 object in references-> COM tab

namespace Sandbox
{
    public class Read_From_Excel
    {
        public static void getExcelFile()
        {

            //Create COM Objects. Create a COM object for everything that is referenced
            Excel.Application xlApp = new Excel.Application();
            Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"C:\Users\E56626\Desktop\Teddy\VS2012\Sandbox\sandbox_test - Copy - Copy.xlsx");
            Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
            Excel.Range xlRange = xlWorksheet.UsedRange;

            int rowCount = xlRange.Rows.Count;
            int colCount = xlRange.Columns.Count;

            //iterate over the rows and columns and print to the console as it appears in the file
            //excel is not zero based!!
            for (int i = 1; i <= rowCount; i++)
            {
                for (int j = 1; j <= colCount; j++)
                {
                    //new line
                    if (j == 1)
                        Console.Write("\r\n");

                    //write the value to the console
                    if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null)
                        Console.Write(xlRange.Cells[i, j].Value2.ToString() + "\t");
                }
            }

            //cleanup
            GC.Collect();
            GC.WaitForPendingFinalizers();

            //rule of thumb for releasing com objects:
            //  never use two dots, all COM objects must be referenced and released individually
            //  ex: [somthing].[something].[something] is bad

            //release com objects to fully kill excel process from running in the background
            Marshal.ReleaseComObject(xlRange);
            Marshal.ReleaseComObject(xlWorksheet);

            //close and release
            xlWorkbook.Close();
            Marshal.ReleaseComObject(xlWorkbook);

            //quit and release
            xlApp.Quit();
            Marshal.ReleaseComObject(xlApp);
        }
    }
}   

Làm thế nào đọc và ghi dữ liệu từ Excel trong C#?

Các bước để đọc và ghi dữ liệu từ Excel bằng C#..
Bước 1: Tạo một dự án C# mới trong Visual Studio. ....
Bước 2: Thêm tham chiếu thành phần COM, tức là Excel 14 Đối tượng. ....
Bước 3: Nhập các không gian tên trong mã C#. ....
Bước 4: Viết dữ liệu vào tệp Excel. ....
Bước 5: Đọc dữ liệu từ tệp Excel. ....
Bước 6: Chạy chương trình C# ..

Excelpackage C#là gì?

Đại diện cho gói tệp XLSX Excel 2007/2010. Đây là đối tượng cấp cao nhất để truy cập tất cả các phần của tài liệu.. This is the top-level object to access all parts of the document.

Làm thế nào đọc dữ liệu từ Excel trong C# bằng OpenXML?

Mã C#..
được bảo vệ void insertboqelements_click (người gửi đối tượng, EventArgs E).
// Chỉ định tên tệp nơi nó thực sự tồn tại ..
Chuỗi filePath = @ "d: \ tpms \ uploaded_boq \ test.xlsx" ;.
// Mở Excel bằng SDK OpenXML ..
sử dụng (bảng tínhDocument doc = bảng tínhDocument.open (filepath, false)).

IronXL có miễn phí không?

Khóa giấy phép IronXL cho phép bạn triển khai dự án trực tiếp mà không cần bất kỳ hình mờ nào.Giấy phép bắt đầu chỉ $ 499 và bao gồm một năm hỗ trợ và cập nhật miễn phí.Bạn cũng có thể thử IronXL miễn phí trong 30 ngày với khóa cấp phép dùng thử.You can also try IronXL free for 30 days with a trial license key.