2012-06-23 5 views

답변

8

그냥 당신이 ... vb.net 같은 몇 가지 중 하나 감사 나에게 좋은 일을 위해 모든

Microsoft.Office.Interop.Excel.Application excel = null; 
Microsoft.Office.Interop.Excel.Workbook wb = null; 

object missing = Type.Missing; 
Microsoft.Office.Interop.Excel.Worksheet ws = null; 
Microsoft.Office.Interop.Excel.Range rng = null;  

try 
{ 
    excel = new Microsoft.Office.Interop.Excel.Application(); 
    wb = excel.Workbooks.Add(); 
    ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.ActiveSheet; 

    for (int Idx = 0; Idx < dt.Columns.Count; Idx++) 
    { 
     ws.Range["A1"].Offset[0, Idx].Value = dt.Columns[Idx].ColumnName; 
    } 

    for (int Idx = 0; Idx < dt.Rows.Count; Idx++) 
    { // <small>hey! I did not invent this line of code, 
     // I found it somewhere on CodeProject.</small> 
     // <small>It works to add the whole row at once, pretty cool huh?</small> 
     ws.Range["A2"].Offset[Idx].Resize[1, dt.Columns.Count].Value = 
     dt.Rows[Idx].ItemArray; 
    } 

    excel.Visible = true; 
    wb.Activate(); 
} 
catch (COMException ex) 
{ 
    MessageBox.Show("Error accessing Excel: " + ex.ToString()); 
} 
catch (Exception ex) 
{ 
    MessageBox.Show("Error: " + ex.ToString()); 
} 
+3

감사합니다! 좋은 본보기. :) – asuciu

4

데이터 테이블에서 .csv (쉼표로 구분 된 값 파일)를 저장할 수 있습니다. 이 파일은 Excel에서 열 수 있습니다.

더욱이 : WPF 또는 Winforms이든, 변환 코드가 사용자의 언어 (예 : C#)로 작성되었으며 WPF 또는 Winforms에만 국한되지 않으므로 변환은 둘 다 동일합니다.

2

을 위해, 더 나은 가시로?

Dim excel As Microsoft.Office.Interop.Excel.Application = Nothing 
Dim wb As Microsoft.Office.Interop.Excel.Workbook = Nothing 

Dim missing As Object = Type.Missing 
Dim ws As Microsoft.Office.Interop.Excel.Worksheet = Nothing 
Dim rng As Microsoft.Office.Interop.Excel.Range = Nothing 

하위 ExcelFile (DataTable을 같이 DT ByVal의)

Try 
     excel = New Microsoft.Office.Interop.Excel.Application() 
     wb = excel.Workbooks.Add() 
     ws = DirectCast(wb.ActiveSheet, Microsoft.Office.Interop.Excel.Worksheet) 

     For Idx As Integer = 0 To dt.Columns.Count - 1 
      ws.Range("A1").Offset(0, Idx).Value = dt.Columns(Idx).ColumnName 
     Next 

     For Idx As Integer = 0 To dt.Rows.Count - 1 
      ' <small>hey! I did not invent this line of code, 
      ' I found it somewhere on CodeProject.</small> 
      ' <small>It works to add the whole row at once, pretty cool huh?</small> 
      ' YES IT'S COOL Brother ... 
      ws.Range("A2").Offset(Idx).Resize(1, dt.Columns.Count).Value = dt.Rows(Idx).ItemArray 
     Next 

     excel.Visible = True 
     wb.Activate() 
    Catch ex As Exception 
     MessageBox.Show("Error accessing Excel: " & ex.ToString()) 

    End Try 

End Sub 
관련 문제