developer tip

C #을 사용하여 Excel 파일에서 데이터를 읽는 방법

optionbox 2020. 12. 15. 19:02
반응형

C #을 사용하여 Excel 파일에서 데이터를 읽는 방법


이 질문에 이미 답변이 있습니다.

내 응용 프로그램은 Excel 파일에서 데이터를 읽어야합니다. 개발을 위해 .Net 및 C #을 사용하고 있습니다. 시스템에 MS 오피스를 설치할 수 없습니다. 그 때문에 내 응용 프로그램이 Excel 파일을 읽지 못하고 Excel 용 dll을로드하는 동안 오류가 발생합니다.

MS Office가 설치되지 않은 시스템에서 내 애플리케이션의 Excel 파일에 액세스하려면 어떻게해야합니까?


OleDB데이터베이스의 데이터 테이블과 같은 Excel 시트 를 사용 하고 사용 하는 옵션이 있습니다 .

예 .....

string con =
  @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\temp\test.xls;" + 
  @"Extended Properties='Excel 8.0;HDR=Yes;'";    
using(OleDbConnection connection = new OleDbConnection(con))
{
    connection.Open();
    OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", connection); 
    using(OleDbDataReader dr = command.ExecuteReader())
    {
         while(dr.Read())
         {
             var row1Col0 = dr[0];
             Console.WriteLine(row1Col0);
         }
    }
}

이 예에서는 Microsoft.Jet.OleDb.4.0공급자를 사용 하여 Excel 파일을 열고 읽습니다. 그러나 파일이 xlsx 유형 (Excel 2007 이상) 인 경우 Microsoft Access 데이터베이스 엔진 구성 요소 를 다운로드 하여 대상 컴퓨터에 설치해야합니다.

공급자는라고 Microsoft.ACE.OLEDB.12.0;합니다. 이 구성 요소에는 32 비트 용과 64 비트 용의 두 가지 버전이 있다는 사실에주의하십시오. 응용 프로그램의 비트와 설치된 Office 버전 (있는 경우)에 적합한 버전을 선택합니다. 해당 드라이버가 응용 프로그램에서 올바르게 작동하도록하는 데는 많은 단점이 있습니다. 예를 들어이 질문을 참조하십시오 .

물론 대상 컴퓨터에 Office를 설치할 필요는 없습니다.

이 접근 방식에는 몇 가지 장점이 있지만, Reading excel files from C # 질문에 주석으로 표시된 링크에 특히주의해야한다고 생각합니다 . 데이터 유형의 올바른 해석과 단일 Excel 셀에있는 데이터 길이가 255자를 초과하는 경우 몇 가지 문제가 있습니다.


Excel 97-2003 파일 (xls) 읽기 용 CSharpJExcel : http://sourceforge.net/projects/jexcelapi/

및 Excel 2007/2010 파일 읽기 용 ExcelPackage (Office Open XML 형식, xlsx) : http://excelpackage.codeplex.com/

및 ExcelDataReader는 두 형식을 모두 처리 할 수있는 것으로 보입니다 : https://github.com/ExcelDataReader/ExcelDataReader

행운을 빕니다!


이것을 테스트 할 수있는 컴퓨터가 없지만 작동합니다. 먼저 2007 Office System 드라이버 : 데이터 연결 구성 요소 또는 Microsoft Access 데이터베이스 엔진 2010 재배포 가능 패키지 를 설치해야 할 것입니다 . 그런 다음 다음 코드를 시도하십시오. Excel 파일의 시트 이름과 일치하도록 아래 Select 문에서 시트 이름을 변경해야합니다.

using System.Data;
using System.Data.OleDb;

namespace Data_Migration_Process_Creator
{
    class Class1
    {
        private DataTable GetDataTable(string sql, string connectionString)
        {
            DataTable dt = null;

            using (OleDbConnection conn = new OleDbConnection(connectionString))
            {
                conn.Open();
                using (OleDbCommand cmd = new OleDbCommand(sql, conn))
                {
                    using (OleDbDataReader rdr = cmd.ExecuteReader())
                    {
                        dt.Load(rdr);
                        return dt;
                    }
                }
            }
        }

        private void GetExcel()
        {
            string fullPathToExcel = "<Path to Excel file>"; //ie C:\Temp\YourExcel.xls
            string connString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=yes'", fullPathToExcel);
            DataTable dt = GetDataTable("SELECT * from [SheetName$]", connString);

            foreach (DataRow dr in dt.Rows)
            {
                //Do what you need to do with your data here
            }
        }
    }
}

참고 : (Office가 설치된 One)에서 테스트 할 환경이 없으므로 사용자 환경에서 작동할지 여부는 말할 수 없지만 작동하지 않는 이유는 알 수 없습니다.


Excel 파일을 CSV로 저장하고 FileHelpers 와 같은 CSV 판독기 라이브러리를 사용하여 C #으로 결과 파일을 읽습니다 .


Convert the excel file to .csv file (comma separated value file) and now you can easily be able to read it.

ReferenceURL : https://stackoverflow.com/questions/15793442/how-to-read-data-from-excel-file-using-c-sharp

반응형