수색…


소개

POI Java 프로젝트의 .NET 버전입니다. Microsoft Office를 설치하지 않고 xls, doc, ppt 파일을 읽고 쓸 수 있습니다. 설명서에 대한 자세한 내용은 https://github.com/tonyqus/npoi에서 확인할 수 있습니다.

NPOI 설치

NPOI와 관련된 모든 라이브러리를 포함하는 가장 좋은 방법은 NUGet Package Manager입니다. NUGet 패키지 관리자 창에서 NPOI를 검색하십시오.

여기에 이미지 설명을 입력하십시오.

설치가 완료되면 필요한 모든 라이브러리가 현재 프로젝트의 참조 섹션에 나타납니다. 여기에 이미지 설명을 입력하십시오.

그런 다음이 파일에 NPOI를 포함 시키십시오.

using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel

Excel 파일 만들기

MemoryStream excelMS =  GetExcelFile();
 
 //Using Resposne Stream to Make File Available for User to Download;
 Response.Clear();
 Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
 Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", @"Excel_" + DateTime.Now.ToString("yyyy-dd-M-HH-mm") + ".xlsx"));

 Response.BinaryWrite(excelMS.ToArray());
 Response.End();

MIME 유형을 사용하는 동안주의하십시오. 다른 파일 형식에 대해 다른 MIME 유형을 선택해야합니다. EX xltm 확장의 경우 "application / vnd.ms-excel.template.macroEnabled.12"; xlxs 확장은 "application / vnd.openxmlformats-officedocument.spreadsheetml.sheet"가 될 것입니다; 지원되는 다른 MIME 유형이 링크에있는 MS입니다.

public MemoryStream GetExcelFile()
{
    //Excel File Stream 
    MemoryStream ms = null;
    // create workbook
    XSSFWorkbook workbook = new XSSFWorkbook();
    // the table named mySheet
    //Assigning New Sheet Name /
    XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet("WorkSheet");
       
    // Assuming FreezePaneRow  = 10, FreezePaneColumn = 11 in the config file
    int freezeRow = Convert.ToInt32(ConfigurationManager.AppSettings["FreezePaneRow"]);
    int freezeCol = Convert.ToInt32(ConfigurationManager.AppSettings["FreezePaneCol"]);
    try
    {
        // Freeze Created Excel Sheet Row;
            sheet.CreateFreezePane(freezeCol, freezeRow, freezeCol, freezeRow);
        //Freezing only the Header Row;
            sheet.CreateFreezePane(0, 1);

         using (ms = new MemoryStream())
            {
                logger.Info("Using Memory Stream to Create New WorkBook");
                workbook.Write(ms); // Write to memory stream for download through browser     
            }
    }
    catch (Exception Ex)
    { ... }
    return ms;
}

Excel 파일 읽기

엑셀 파일을 읽는 방법은 다양합니다. 파일 경로 매개 변수 예제를 제공합니다. 게시물에서 다양한 방법으로 파일을 읽을 수 있습니다.

public void ReadExcel(string path)
        {
            // Write data in workbook from xls document.
            XSSFWorkbook workbook = new XSSFWorkbook(path);
            // Read the current table data
            XSSFSheet sheet = (XSSFSheet)workbook.GetSheetAt(0);
            // Read the current row data
            XSSFRow headerRow = (XSSFRow)sheet.GetRow(0);
            // LastCellNum is the number of cells of current rows
            int cellCount = headerRow.LastCellNum;
            DataTable dt = new DataTable();
            bool isBlanKRow = false;

            try
            {
                if (dt.Rows.Count == 0)
                {
                    //Reading First Row as Header for Excel Sheet;
                    try
                    {
                        for (int j = headerRow.FirstCellNum; j < cellCount; j++)
                        {
                            // get data as the column header of DataTable
                            DataColumn column = new DataColumn(headerRow.GetCell(j).StringCellValue);
                            dt.Columns.Add(column);
                        }
                    }
                    catch (Exception Ex)
                    { }
                }

                for (int sheetindex = 0; sheetindex < workbook.NumberOfSheets; sheetindex++)
                {
                    sheet = (XSSFSheet)workbook.GetSheetAt(sheetindex);
                    if (null != sheet)
                    {
                        // LastRowNum is the number of rows of current table
                        int rowCount = sheet.LastRowNum + 1;
                        //Reading Rows and Copying it to Data Table;
                        try
                        {
                            for (int i = (sheet.FirstRowNum + 1); i < rowCount; i++)
                            {
                                XSSFRow row = (XSSFRow)sheet.GetRow(i);
                                DataRow dataRow = dt.NewRow();
                                isBlanKRow = true;
                                try
                                {
                                    for (int j = row.FirstCellNum; j < cellCount; j++)
                                    {
                                        if (null != row.GetCell(j) && !string.IsNullOrEmpty(row.GetCell(j).ToString()) && !string.IsNullOrWhiteSpace(row.GetCell(j).ToString()))
                                        {
                                            dataRow[j] = row.GetCell(j).ToString();
                                            isBlanKRow = false;
                                        }

                                    }
                                }
                                catch (Exception Ex)
                                { }
                                if (!isBlanKRow)
                                {
                                    dt.Rows.Add(dataRow);
                                }
                            }
                        }
                        catch (Exception Ex)
                        { }
                    }
                }
            }
            catch (Exception Ex)
            { }
            finally
            {
                workbook.UnlockStructure();
                workbook.UnlockRevision();
                workbook.UnlockWindows();
                workbook = null;
                sheet = null;
            }
        }


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow