2012-02-18 2 views
2

내 수출 코드DataGridview 데이터를 내보내 Excel로 내보내는 방법?

이 코드는 Excel에서 데이터를 쓰지만 내용이 셀에 들어가 있습니다. 그들은 흩어져있다.

public static void export_to_excel(DataGridView dgv, string excel_file) 
    { 
     int cols; 
     //open file 
     StreamWriter wr = new StreamWriter(excel_file); 
     cols = dgv.Columns.Count; 
     for (int i = 0; i < cols; i++) 
     { 
      wr.Write(dgv.Columns[i].HeaderText.ToString().ToUpper() + "\t"); 
     } 
     wr.WriteLine(); //write rows to excel file 

     for (int i = 0; i < (dgv.Rows.Count - 1); i++) 
     { 
      for (int j = 0; j < cols; j++) 
      { 
       if (dgv.Rows[i].Cells[j].Value != null) 
        wr.Write(dgv.Rows[i].Cells[j].Value + "\t"); 
       else 
       { 
        wr.Write("\t"); 
       } 
      } 
      wr.WriteLine(); 
     } 
     //close file 
     wr.Close(); } 

답변

1

내가 VB.net에서, 나는 http://www.developerfusion.com/tools/convert/vb-to-csharp/와 C#을로 변환하는 것이했던, 그래서 당신은 그것을 테스트해야합니다.

VB.net 코드 :

Imports System.Runtime.CompilerServices 
Imports Excel = Microsoft.Office.Interop.Excel 
Public Module ExcelMod 

    <Extension()> _ 
    Public Function ToExcel(ByVal grd As DataGridView, ByVal path As String, Optional ByRef exp As Exception = Nothing) As Boolean 
     Dim res As Boolean = False 
     exp = Nothing 
     Dim xlApp As Excel.Application = Nothing 
     Dim xlWorkBook As Excel.Workbook = Nothing 
     Dim xlWorkSheet As Excel.Worksheet = Nothing 
     Try 

      Dim oldCI As System.Globalization.CultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture 

      Dim misValue As Object = System.Reflection.Missing.Value 
      Dim i As Integer 
      Dim j As Integer 

      xlApp = New Excel.ApplicationClass 
      System.Threading.Thread.CurrentThread.CurrentCulture = New System.Globalization.CultureInfo("en-US") 

      xlWorkBook = xlApp.Workbooks.Add(misValue) 
      xlWorkSheet = xlWorkBook.Sheets("sheet1") 

      Dim lastCol As Integer = 0 
      Dim lastRow As Integer = 0 
      For j = 0 To grd.ColumnCount - 1 
       If grd.Columns(j).Visible Then 
        xlWorkSheet.Columns(lastCol + 1).ColumnWidth = CInt(grd.Columns(j).Width/10) 
        xlWorkSheet.Cells(1, lastCol + 1) = grd.Columns(j).HeaderText 
        lastCol += 1 
       End If 
      Next 

      lastRow = 0 
      For i = 0 To grd.RowCount - 1 
       lastCol = 0 
       For j = 0 To grd.ColumnCount - 1 
        If grd.Columns(j).Visible AndAlso grd.Rows(i).Visible Then 

         If grd(j, i).FormattedValue <> Nothing Then _ 
          xlWorkSheet.Cells(lastRow + 2, lastCol + 1) = grd(j, i).FormattedValue.ToString() 

         lastCol += 1 

        End If 
       Next 
       If grd.Rows(i).Visible Then lastRow += 1 
      Next 


      xlWorkSheet.SaveAs(path) 
      xlWorkBook.Close() 
      xlApp.Quit() 

      System.Threading.Thread.CurrentThread.CurrentCulture = oldCI 
      res = True 

     Catch ex As Exception 
      exp = ex 
     Finally 
      If xlApp IsNot Nothing Then releaseObject(xlApp) 
      If xlWorkBook IsNot Nothing Then releaseObject(xlWorkBook) 
      If xlWorkSheet IsNot Nothing Then releaseObject(xlWorkSheet) 
     End Try 

     Return res 
    End Function 

    Private Sub releaseObject(ByVal obj As Object) 
     Try 
      System.Runtime.InteropServices.Marshal.ReleaseComObject(obj) 
      obj = Nothing 
     Catch ex As Exception 
      obj = Nothing 
     Finally 
      GC.Collect() 
     End Try 
    End Sub 

End Module 

C# 코드 :

using Microsoft.VisualBasic; 
using System; 
using System.Collections; 
using System.Collections.Generic; 
using System.Data; 
using System.Diagnostics; 
using System.Runtime.CompilerServices; 
using Excel = Microsoft.Office.Interop.Excel; 
public static class ExcelMod 
{ 


    public static bool ToExcel(this DataGridView grd, string path, ref Exception exp = null) 
    { 
     bool res = false; 
     exp = null; 
     Excel.Application xlApp = null; 
     Excel.Workbook xlWorkBook = null; 
     Excel.Worksheet xlWorkSheet = null; 

     try { 
      System.Globalization.CultureInfo oldCI = System.Threading.Thread.CurrentThread.CurrentCulture; 

      object misValue = System.Reflection.Missing.Value; 
      int i = 0; 
      int j = 0; 

      xlApp = new Excel.ApplicationClass(); 
      System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US"); 

      xlWorkBook = xlApp.Workbooks.Add(misValue); 
      xlWorkSheet = xlWorkBook.Sheets("sheet1"); 

      int lastCol = 0; 
      int lastRow = 0; 
      for (j = 0; j <= grd.ColumnCount - 1; j++) { 
       if (grd.Columns(j).Visible) { 
        xlWorkSheet.Columns(lastCol + 1).ColumnWidth = Convert.ToInt32(grd.Columns(j).Width/10); 
        xlWorkSheet.Cells(1, lastCol + 1) = grd.Columns(j).HeaderText; 
        lastCol += 1; 
       } 
      } 

      lastRow = 0; 
      for (i = 0; i <= grd.RowCount - 1; i++) { 
       lastCol = 0; 
       for (j = 0; j <= grd.ColumnCount - 1; j++) { 

        if (grd.Columns(j).Visible && grd.Rows(i).Visible) { 
         if (grd(j, i).FormattedValue != null) 
          xlWorkSheet.Cells(lastRow + 2, lastCol + 1) = grd(j, i).FormattedValue.ToString(); 

         lastCol += 1; 

        } 
       } 
       if (grd.Rows(i).Visible) 
        lastRow += 1; 
      } 


      xlWorkSheet.SaveAs(path); 
      xlWorkBook.Close(); 
      xlApp.Quit(); 

      System.Threading.Thread.CurrentThread.CurrentCulture = oldCI; 
      res = true; 

     } catch (Exception ex) { 
      exp = ex; 
     } finally { 
      if (xlApp != null) 
       releaseObject(xlApp); 
      if (xlWorkBook != null) 
       releaseObject(xlWorkBook); 
      if (xlWorkSheet != null) 
       releaseObject(xlWorkSheet); 
     } 

     return res; 
    } 

    private static void releaseObject(object obj) 
    { 
     try { 
      System.Runtime.InteropServices.Marshal.ReleaseComObject(obj); 
      obj = null; 
     } catch (Exception ex) { 
      obj = null; 
     } finally { 
      GC.Collect(); 
     } 
    } 

} 
+0

당신이 당신의 코드 – Laxminarayan

+0

에 대해 나에게 브리핑 할 수 단순히 그것은 VB.net –

+0

나에게 투표하세요 호출하려면 당신의 투표를 위해 –

0

흩어져있는 이유 어떤것 당신이 탭 (\의 t) 분리, 사용 ","구분 기호를 사용하고 있다는 점이다. 값만 내보내려면 파일을 CSV 파일로 내 보내야합니다. 장점 : - Excel을 설치할 필요가 없습니다. - COM interop 호출이 필요 없습니다. (그런데 코드가 단일 스레드로 만들어지며 다중 CPU/스레드에 맞게 확장되지 않습니다.) - Excel에서 CSV 파일을 직접 읽을 수 있습니다.

수출 코드 :이 작업의 경우

public static void export_to_excelAsCsvFile(DataGridView dGV, string filename) 
    { 
     string separator = ","; 
     StringBuilder stOutput = new StringBuilder(); 
     // Export titles: 
     StringBuilder sHeaders = new StringBuilder(); 
     for (int j = 0; j < dGV.Columns.Count; j++) 
     { 
      sHeaders.Append(dGV.Columns[j].HeaderText); 
      sHeaders.Append(separator); 
     } 
     stOutput.AppendLine(sHeaders.ToString()); 
     // Export data. 
     for (int i = 0; i < dGV.RowCount - 1; i++) 
     { 
      StringBuilder stLine = new StringBuilder(); 
      for (int j = 0; j < dGV.ColumnCount; j++) 
      { 
       stLine.Append(Convert.ToString(dGV[j, i].Value)); 
       stLine.Append(separator); 
      } 
      stOutput.AppendLine(stLine.ToString()); 
     } 

     File.WriteAllText(filename, stOutput.ToString()); 
    } 
관련 문제