2013-06-19 3 views
0

데이터 테이블을 채우는 DataGrid가 있는데, 버튼 클릭만으로 Excel에서 DataTable을 내보내고 싶습니다. 이 응용 프로그램에 MVVM을 사용하고 있습니다. 내보기에서 내보내기 기능을 구현해도 괜찮습니까?DataTable to convert conversion

둘째, xaml과 데스크톱 응용 프로그램을 사용할 때 그리드와 그 세부 사항을 어떻게 캡처합니까?

어떤 조언을 해줄 수 있습니까? 나는 이것에 초보적이다.

감사 사가르

+0

봐 (http://closedxml.codeplex.com/) 제 3 자 라이브러리는 코드의 일부를 정리하는데 도움이됩니다. – KyleMit

+0

@KyleMit ClosedXML은 ASP.net 기반입니다.이 기능은 mvvm 아키텍처에서 xaml 컨트롤을 사용하는 응용 프로그램에서 필요합니다. – voonna

답변

1

에서 좋은 답변이 내가 한 일이다 그리고 그것은 나에게 도움이 : A와 [ClosedXML]에서

private readonly ICommand m_ExportButtonClick; 
    private string ExcelFilePath = ""; 

    public ICommand ExportButtonClick { get { return m_ExportButtonClick; } } 

    private void OnRunExport() 
    { 
     try 
     { 
      if (queryDatatable == null || queryDatatable.Columns.Count == 0) 
       throw new Exception("ExportToExcel: Null or empty input table!\n"); 

      // load excel, and create a new workbook 
      Excell.Application excelApp = new Excell.Application(); 
      excelApp.Workbooks.Add(); 

      // single worksheet 
      Excell._Worksheet workSheet = excelApp.ActiveSheet; 

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

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

      // check fielpath 
      if (ExcelFilePath != null && 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 filepath is given, the file opens up and the user can save it accordingly. 
      { 
       excelApp.Visible = true; 
      } 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show("There is no data to export. Please check your query/ Contact administrator." + ex.Message); 
     } 
    }  
    #endregion 
0

여기 (열 수 엑셀)을 CSV 어떤 DataTable의 출력의 확장 방법

Imports System.Text 
Imports System.IO 
Imports System.Runtime.CompilerServices 

Module ExtensionMethods 

    <Extension()> _ 
    Public Sub OutputAsCSV(ByVal dt As DataTable, ByVal filePath As String) 
     Dim sb As New StringBuilder() 

       'write column names to string builder 
     Dim columnNames As String() = (From col As DataColumn In dt.Columns Select col.ColumnName).ToArray 
     sb.AppendLine(String.Join(",", columnNames)) 

       'write cell value in each row to string builder 
     For Each row As DataRow In dt.Rows 
      Dim fields As String() = (From cell In row.ItemArray Select CStr(cell)).ToArray 
      sb.AppendLine(String.Join(",", fields)) 
     Next 

       'write string builder to file 
     File.WriteAllText(filePath, sb.ToString()) 
    End Sub 

End Module 
0

약간 주변 검색하는 시도이다. 이것은 매우 일반적인 문제이며 이미 많은 질문을 받았습니다. 다음은이 SO question

public static void ExportToExcel<T>(IEnumerable<T> exportData) 
{ 
    Excel.ApplicationClass excel = new Excel.ApplicationClass(); 
    Excel.Workbook workbook = excel.Application.Workbooks.Add(true); 
    PropertyInfo[] pInfos = typeof(T).GetProperties(); 
    if (pInfos != null && pInfos.Count() > 0) 
    { 
     int iCol = 0; 
     int iRow = 0; 
     foreach (PropertyInfo eachPInfo in pInfos.Where(W => W.CanRead == true)) 
     { 
      // Add column headings... 
      iCol++; 
      excel.Cells[1, iCol] = eachPInfo.Name; 
     } 
     foreach (T item in exportData) 
     { 
      iRow++; 
      // add each row's cell data... 
      iCol = 0; 
      foreach (PropertyInfo eachPInfo in pInfos.Where(W => W.CanRead == true)) 
      { 
       iCol++; 
       excel.Cells[iRow + 1, iCol] = eachPInfo.GetValue(item, null); 
      } 

     } 
     // Global missing reference for objects we are not defining... 
     object missing = System.Reflection.Missing.Value; 
     // If wanting to Save the workbook... 
     string filePath = System.IO.Path.GetTempPath() + DateTime.Now.Ticks.ToString() + ".xlsm"; 
     workbook.SaveAs(filePath, Excel.XlFileFormat.xlOpenXMLWorkbookMacroEnabled, missing, missing, false, false, Excel.XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing, missing); 
     // If wanting to make Excel visible and activate the worksheet... 
     excel.Visible = true; 
     Excel.Worksheet worksheet = (Excel.Worksheet)excel.ActiveSheet; 
     excel.Rows.EntireRow.AutoFit(); 
     excel.Columns.EntireColumn.AutoFit(); 
     ((Excel._Worksheet)worksheet).Activate(); 
    } 
} 
+0

감사합니다. 닷넷 프레임 워크 4.0을 사용하고 있으며 ApplicationClass가 4.0에서 지원되지 않는다고 생각합니다. 내가 리팩토링을 시도 할 때, 그렇게하지 못하게합니다. – voonna