NPOI 작업 EXCEL의 간단한 예

1.DataTable을 XLS 파일로 생성
단독 클래스로 썼어요.
        public static void Import(DataTable dt, string filename)
        {
            // 
            HSSFWorkbook workbook = new HSSFWorkbook();
            // 
            HSSFSheet sheet1 = workbook.CreateSheet("sheet1");
            HSSFSheet sheet2 = workbook.CreateSheet("sheet2");
            HSSFSheet sheet3 = workbook.CreateSheet("sheet3");
            HSSFRow headrow = sheet1.CreateRow(0);// 
            // DataTable 
            foreach (DataColumn column in dt.Columns)
            {
                //column.Oradinal, ,column.ColumnName, 
                headrow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);// 
              
            }

            //  
            HSSFRow row;
            for (int i = 0; i < dt.Rows.Count;i++ )
            {
                row = sheet1.CreateRow(i + 1);
                for (int j = 0; j < dt.Columns.Count;j++ )
                {
                    row.CreateCell(j).SetCellValue(dt.Rows[i][j].ToString());//dataTable EXCEL .
                }

            }

            using(FileStream file=new FileStream(@"d:\"+filename+"",FileMode.Create))
            {
                workbook.Write(file);// 
                file.Dispose();
                
            }
        
        }

 
호출할 때 간단한
 DataTable dt=SqlHelper.ExecuteAdapter("select id as ' ',name as ' ',bus as ' ',tel as ' ' from Employee");
           NPOIDataTable.Import(dt,"16.xls");


 
2. EXCEL DataTable에 쓰기
  public static DataTable ImportData(string filename)
        {
            DataTable dt=new DataTable();
            HSSFWorkbook workbook;
            using(FileStream file=new FileStream(filename,FileMode.Open,FileAccess.Read))
            {
              workbook=new HSSFWorkbook(file);// Steam 
            }

            HSSFSheet sheet = workbook.GetSheetAt(0);// 
            HSSFRow headrow = sheet.GetRow(0);// 
            HSSFCell cell;
            for (int i = 0; i < headrow.LastCellNum; i++)
            {
                cell = headrow.GetCell(i);
                dt.Columns.Add(cell.ToString());
            
            }

            for (int i = 0; i < sheet.LastRowNum; i++)
            {
                HSSFRow row = sheet.GetRow(i + 1);
                DataRow datarow = dt.NewRow();// 
                for (int j = row.FirstCellNum; j < row.LastCellNum;j++ )
                {
                    datarow[j] = row.GetCell(j).ToString();// , 
                }
                dt.Rows.Add(datarow);
            }


                return dt;

        }

 
 

좋은 웹페이지 즐겨찾기