Development Tip

Excel 파일 (.xls / .xlsx)을 읽는 최적의 방법

yourdevel 2020. 11. 21. 09:12
반응형

Excel 파일 (.xls / .xlsx)을 읽는 최적의 방법


Excel 파일을 읽는 방법에는 여러 가지가 있습니다.

  • Iterop
  • Oledb
  • Open Xml SDK

프로그램이 통제 된 환경에서 실행되기 때문에 호환성은 문제가되지 않습니다.

내 요구 사항 :
파일을 DataTable/ CUstom Entities 로 읽습니다 (동적 속성 / 필드를 개체에 만드는 방법을 모릅니다 [열 이름은 Excel 파일에서 변경됨]).

사용 DataTable/Custom Entities데이터를 사용하여 일부 작업을 수행 할 수 있습니다.

DataTable작업 결과 업데이트

에 다시 씁니다 excel file.

더 간단합니다.

또한 가능한 경우 사용자 지정 엔터티에 대한 조언 (동적으로 개체에 속성 / 필드 추가)


Linq-to-Excel을 살펴보십시오 . 꽤 깔끔합니다.

var book = new LinqToExcel.ExcelQueryFactory(@"File.xlsx");

var query =
    from row in book.Worksheet("Stock Entry")
    let item = new
    {
        Code = row["Code"].Cast<string>(),
        Supplier = row["Supplier"].Cast<string>(),
        Ref = row["Ref"].Cast<string>(),
    }
    where item.Supplier == "Walmart"
    select item;

또한 강력한 형식의 행 액세스도 허용합니다.


OLE 쿼리를 사용하면 매우 간단합니다 (예 : sheetName은 Sheet1 임).

DataTable LoadWorksheetInDataTable(string fileName, string sheetName)
{           
    DataTable sheetData = new DataTable();
    using (OleDbConnection conn = this.returnConnection(fileName))
    {
       conn.Open();
       // retrieve the data using data adapter
       OleDbDataAdapter sheetAdapter = new OleDbDataAdapter("select * from [" + sheetName + "$]", conn);
       sheetAdapter.Fill(sheetData);
       conn.Close();
    }                        
    return sheetData;
}

private OleDbConnection returnConnection(string fileName)
{
    return new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + "; Jet OLEDB:Engine Type=5;Extended Properties=\"Excel 8.0;\"");
}

최신 Excel 버전의 경우 :

return new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=Excel 12.0;");

CodePlex에서 오픈 소스 프로젝트 인 Excel Data Reader를 사용할 수도 있습니다 . Excel 시트에서 데이터를 내보내는 데 정말 잘 작동합니다.

지정된 링크에 제공된 샘플 코드 :

FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);

//1. Reading from a binary Excel file ('97-2003 format; *.xls)
IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
//...
//2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
//...
//3. DataSet - The result of each spreadsheet will be created in the result.Tables
DataSet result = excelReader.AsDataSet();
//...
//4. DataSet - Create column names from first row
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();

//5. Data Reader methods
while (excelReader.Read())
{
//excelReader.GetInt32(0);
}

//6. Free resources (IExcelDataReader is IDisposable)
excelReader.Close();

참조 : Microsoft.Office.Interop.Excel을 사용하여 Excel에서 DataSet으로 가져 오려면 어떻게해야합니까?


이 질문은 거의 7 년 전에 질문되었지만 여전히 C #으로 엑셀 데이터를 가져 오는 것과 관련하여 특정 키워드에 대한 Google 검색 결과가 가장 높기 때문에 최근 기술 개발을 기반으로 한 대안을 제공하고 싶었습니다.

Excel 데이터 가져 오기는 일상적인 업무에서 매우 일반적인 작업이되어 프로세스를 간소화하고 블로그에 방법을 문서화했습니다 . c #에서 Excel 파일을 읽는 가장 좋은 방법 입니다.

NPOI를 사용 하는 이유는 Microsoft Office를 설치하지 않고도 Excel 파일을 읽고 쓸 수 있고 COM + 또는 interops를 사용하지 않기 때문입니다. 즉, 클라우드에서 작동 할 수 있습니다!

하지만 진짜 마술은 Donny Tian의 NPOI Mapper와 짝을 이루어 코드를 작성하지 않고도 Excel 열을 C # 클래스의 속성에 매핑 할 수 있기 때문입니다. 아름다워요.

기본 아이디어는 다음과 같습니다.

관심있는 Excel 열과 일치 / 매핑되는 .net 클래스를 만듭니다.

        class CustomExcelFormat
        {
            [Column("District")]
            public int District { get; set; }

            [Column("DM")]
            public string FullName { get; set; }

            [Column("Email Address")]
            public string EmailAddress { get; set; }

            [Column("Username")]
            public string Username { get; set; }

            public string FirstName
            {
                get
                {
                    return Username.Split('.')[0];
                }
            }

            public string LastName
            {
                get
                {
                    return Username.Split('.')[1];
                }
            }
        }

원하는 경우 열 이름을 기반으로 매핑 할 수 있습니다.

그런 다음 엑셀 파일을 처리 할 때 다음과 같이하면됩니다.

        public void Execute(string localPath, int sheetIndex)
        {
            IWorkbook workbook;
            using (FileStream file = new FileStream(localPath, FileMode.Open, FileAccess.Read))
            {
                workbook = WorkbookFactory.Create(file);
            }

            var importer = new Mapper(workbook);
            var items = importer.Take<CustomExcelFormat>(sheetIndex);
            foreach(var item in items)
            {
                var row = item.Value;
                if (string.IsNullOrEmpty(row.EmailAddress))
                    continue;

                UpdateUser(row);
            }

            DataContext.SaveChanges();
        }

이제 내 코드는 Excel 파일 자체를 수정하지 않습니다. 대신 Entity Framework를 사용하여 데이터베이스에 데이터를 저장합니다 (이것이 제 예에서 "UpdateUser"및 "SaveChanges"를 보는 이유입니다). 그러나 NPOI를 사용하여 파일저장 / 수정하는 방법에 대한 좋은 토론이 이미 있습니다.


이 무료 방법을 사용하십시오, https://freenetexcel.codeplex.com

 Workbook workbook = new Workbook();

 workbook.LoadFromFile(@"..\..\parts.xls",ExcelVersion.Version97to2003);
 //Initialize worksheet
 Worksheet sheet = workbook.Worksheets[0];

 DataTable dataTable = sheet.ExportDataTable();

(Open Office XML 형식) * .xlsx 파일로만 제한 할 수있는 경우 가장 많이 사용되는 라이브러리는 EPPLus 일 것 입니다.

보너스는 다른 종속성이 없다는 것입니다. 너겟을 사용하여 설치하십시오.

Install-Package EPPlus

개인적으로 저는 오픈 소스 및 무료 ExcelMapper 가 작업하기 가장 쉽다는 것을 알았 습니다.

일반적인 Microsoft.Interop 및 OLE 쿼리에 비해 훨씬 간결한 (즉 읽기 쉬운) Excel 파일 읽기 방법을 제공합니다.

1. 주어진 Excel 파일 :

여기에 이미지 설명 입력

2. Person C # 개체를 만듭니다.

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
}

3. ExcelMapper를 사용하여 읽기

  var fileName = @"C:\Temp\Names.xlsx"; // your excel file
  List<Person> people = new ExcelMapper(fileName).Fetch<Person>();

추가 시트 인수를 전달하기 만하면 다른 워크 시트에서 읽을 수도 있습니다.

  var fileName = @"C:\Temp\Names.xlsx"; // your excel file
  List<Person> people = new ExcelMapper(fileName).Fetch<Person>("Sheet2");

NuGet을 사용하여 설치할 수 있습니다.

Install-Package ExcelMapper

면책 조항 : 저는 ExcelMapper와 관련이 없지만 다양한 라이브러리를 시도한 후이 라이브러리가 작업하기 가장 쉽다는 것을 알았습니다.

교육용 비디오-C #에서 Excel 파일을 읽는 방법위의 내용을 보여주는 짧은 동영상 이 있습니다.


Aspose.cells 라이브러리를 사용해보십시오. 꽤 좋습니다.

Install-package Aspose.cells

샘플 코드가 있습니다.

using Aspose.Cells;
using System;

namespace ExcelReader
{
    class Program
    {
        static void Main(string[] args)
        {
            // Replace path for your file
            readXLS(@"C:\MyExcelFile.xls"); // or "*.xlsx"
            Console.ReadKey();
        }

        public static void readXLS(string PathToMyExcel)
        {
            //Open your template file.
            Workbook wb = new Workbook(PathToMyExcel);

            //Get the first worksheet.
            Worksheet worksheet = wb.Worksheets[0];

            //Get cells
            Cells cells = worksheet.Cells;

            // Get row and column count
            int rowCount = cells.MaxDataRow;
            int columnCount = cells.MaxDataColumn;

            // Current cell value
            string strCell = "";

            Console.WriteLine(String.Format("rowCount={0}, columnCount={1}", rowCount, columnCount));

            for (int row = 0; row <= rowCount; row++) // Numeration starts from 0 to MaxDataRow
            {
                for (int column = 0; column <= columnCount; column++)  // Numeration starts from 0 to MaxDataColumn
                {
                    strCell = "";
                    strCell = Convert.ToString(cells[row, column].Value);
                    if (String.IsNullOrEmpty(strCell))
                    {
                        continue;
                    }
                    else
                    {
                        // Do your staff here
                        Console.WriteLine(strCell);
                    }
                }
            }
        }
    }
}

참고 URL : https://stackoverflow.com/questions/12996234/optimal-way-to-read-an-excel-file-xls-xlsx

반응형