2017-03-14 2 views
0

새 열을 기존 워크 시트에 삽입하는 방법을 알고 있습니까?워크 시트에 Excel 열을 추가하는 방법

내 현재 솔루션은 기존 Excel의 모든 열을 복사하여 새로운 Excel 파일을 만든 다음 데이터 표에 새 열을 추가 한 다음 내보내 새 Excel을 만듭니다. 이 방법은 다소 지루하고 단지 기존 컬럼에 새로운 컬럼을 추가하는 것이 내가 보는 최선의 방법입니다. 여기

새로운 엑셀 파일을 생성하기위한 제 기능입니다

public static void ExportToExcel(DataTable tbl) 
    { 
     try 
     { 
      string dateNow = String.Format("{0:MM_dd_yyyy HH_mm_ss}", DateTime.Now); 
      string excelFilePath = "C:\\The_Excel_File\\Result_" + dateNow; 


      if (tbl == null || tbl.Columns.Count == 0) 
       throw new Exception("ExportToExcel: Null or empty input table!\n"); 

      // load excel, and create a new workbook 
      var excelApp = new Microsoft.Office.Interop.Excel.Application(); 
      excelApp.Workbooks.Add(); 

      // single worksheet 
      Microsoft.Office.Interop.Excel._Worksheet workSheet = excelApp.ActiveSheet; 

      // column headings 
      for (var i = 0; i < tbl.Columns.Count; i++) 
      { 
       workSheet.Cells[1, i + 1] = tbl.Columns[i].ColumnName; 
      } 

      // rows 
      for (var i = 0; i < tbl.Rows.Count; i++) 
      { 
       // to do: format datetime values before printing 
       for (var j = 0; j < tbl.Columns.Count; j++) 
       { 
        workSheet.Cells[i + 2, j + 1] = tbl.Rows[i][j]; 
       } 
      } 

      // check file path 
      if (!string.IsNullOrEmpty(excelFilePath)) 
      { 
       try 
       { 
        workSheet.SaveAs(excelFilePath); 
        excelApp.Quit(); 
        //MessageBox.Show("Excel file saved!"); 
       } 
       catch (Exception ex) 
       { 
        throw new Exception("ExportToExcel: Excel file could not be saved! Check filepath.\n" 
             + ex.Message); 
       } 
      } 
      else 
      { // no file path is given 
       excelApp.Visible = true; 
      } 
     } 
     catch (Exception ex) 
     { 
      throw new Exception("ExportToExcel: \n" + ex.Message); 
     } 
    } 

답변

0

를 열고이 값 이하와 비밀 명시된 rangeaddress하는 시트를 엑셀 및 범위를 사용하여 시트를 사용하여 열 개수와 행 개수를 얻을 존재하는 시트를

엑셀 기존의 쓰기
Sheet.UsedRange.Columns.Count 

Sheet.UsedRagne.Rows.Count 
관련 문제