2009-10-06 7 views

답변

5

직접 연결할 방법이 없습니다. LINQ to SQL이 쿼리 생성을 처리하지만 O/R 매핑이 필요하지 않은 것 같습니다 (Excel은 LINQ에서 벗어난 개체를 어떻게 처리해야할지 모르기 때문에 더 이상 데이터 행처럼 보이지 않습니다.)). 첫 번째 부분은 (datacontext) .GetCommand (yourLinqQueryHere)를 호출 한 다음 SqlCommand에서 CommandText로 실행하여 수행 할 수 있습니다. ExecuteReader()를 호출 한 다음 GetSchemaTable()을 호출하여 열의 순서를 찾습니다. 그런 다음 (Excel을 자동화한다고 가정 할 때) (DbDataReader) .GetValues ​​()의 결과를 Excel의 (Worksheet) .Row [x] .Values에 전달하면 결과가 표시됩니다. 물건을 재정렬해야 할 수도 있습니다. Excel을 자동화하지 않는 경우 OleDbConnection과 함께 Excel 용 Jet OLEDB 공급자를 사용하여 값을 덤프하거나 타사 구성 요소를 사용하여 스프레드 시트를 생성해야합니다.

0

가장 빠른 해결책은 CSV 파일을 만들 수있을 것입니다 :

col1, colb, colc 
col1, colb, colc 

엑셀 CSV 파일을 매우 잘 작동합니다.

1

당신은 할 수 있습니다

  • 는 대부분의 시스템에서 엑셀과 연관된 CSV 파일을 만듭니다.
  • Excel 워크 시트 개체를 만들고 수동으로 채 웁니다. Google Search
  • XLS/XLSX 생성 컨트롤 사용. 나는 Spire.XLS를 사용하고있다. http://www.e-iceblue.com/xls/xlsintro.htm
1

Excel Data Object Provider을 보라. 필자는 개인적으로 쓰기 기능을 사용하지 않았으며 서수 식별자 (열 이름도 가능)를 허용하는 읽기 지원을 채택했지만 올바른 방향으로 나아갈 수 있습니다. Excel 2003 이상이 대상 컴퓨터에 설치되어 있지 않으면 XLSX 파일을 쓰거나 읽을 수 없습니다. 표준 XLS 파일은 모든 Windows 상자에서 작동합니다.

서수 열이있는 적응 버전은 here입니다. 코드를 사용하기로 결정한 경우 위의 링크에서 현재 버전에서 구현하는 것이 필요/도움이 될 수 있습니다. 내 버전은 version 2.0과 2.5의 기능을 혼합 한 것으로 모든 읽기 기능 (일부 2.5 업그레이드 포함)이 있지만 글을 쓰지 않습니다. 오 - 그리고 버전 2.0 또는 2.5와 달리, 내 버전에서는 Excel 문서의 첫 번째 시트에 "Sheet1"이라는 이름을 요구하지 않습니다.

희망 하시겠습니까?

0

LINQ로 데이터를 검색한다는 사실은 부적절합니다. Excel을 작성하기에 좋은 라이브러리입니다. 일단 확인한 후에는 결과를 반복하여 Excel 워크 시트에 행을 만들 수 있습니다.

도서관에서까지 나는 NPOI을 사용했으며 훌륭했습니다.

17

저는 개인적으로 언제나 나중에 어떤 시점에서 제한하는 것을 발견하는 등의 일에 도서관을 사용하는 것을 크게 좋아하지 않습니다 ...

나는 열 머리글을 생성하고 각 행의 셀 값을 얻기 위해 리플렉션을 사용했습니다. .NET Framework 3.5를 사용하는 경우 확장 메서드를 활용하여 IEnumerable<object>을 Excel XDocument 파일로 내보낼 수 있습니다. 여기

내가 그것을 어떻게입니다 :이 도움이

public static DownloadableFile ToDownloadableXmlFileForExcel2003(this System.Xml.Linq.XDocument file, string fileName) 
{ 
    MemoryStream ms = new MemoryStream(); 

    XmlWriterSettings xmlWriterSettings = new XmlWriterSettings() { Encoding = Encoding.UTF8 }; 
    XmlWriter xmlWriter = XmlWriter.Create(ms, xmlWriterSettings); 

    file.Save(xmlWriter); //.Save() adds the <xml /> header tag! 
    xmlWriter.Close();  //Must close the writer to dump it's content its output (the memory stream) 

    DownloadableFile dbf = 
      new DownloadableFile 
      { 
       FileName = String.Format("{0}.xls", fileName.Replace(" ", "")), 
       Content = ms.ToArray(), 
       MimeType = "application/vnd.ms-excel" 
      }; 

    ms.Close(); 
    ms.Dispose(); 

    return dbf; 
} 

희망 : 나는 또한 웹 시나리오로하여 XDocument를 돌려 쉽게하기 위해 다른 확장자 방법을 만들었습니다

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Xml.Linq; 

namespace YourNameSpace 
{ 
    public static class ExcelExportExtensions 
    { 
     public static XDocument ToExcelXml(this IEnumerable<object> rows) 
     { 
      return rows.ToExcelXml("Sheet1"); 
     } 

     public static XDocument ToExcelXml(this IEnumerable<object> rows, string sheetName) 
     { 
      sheetName = sheetName.Replace("/", "-"); 
      sheetName = sheetName.Replace("\\", "-"); 

      XNamespace mainNamespace = "urn:schemas-microsoft-com:office:spreadsheet"; 
      XNamespace o = "urn:schemas-microsoft-com:office:office"; 
      XNamespace x = "urn:schemas-microsoft-com:office:excel"; 
      XNamespace ss = "urn:schemas-microsoft-com:office:spreadsheet"; 
      XNamespace html = "http://www.w3.org/TR/REC-html40"; 

      XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes")); 

      var headerRow = from p in rows.First().GetType().GetProperties() 
          select new XElement(mainNamespace + "Cell", 
           new XElement(mainNamespace + "Data", 
            new XAttribute(ss + "Type", "String"), p.Name)); //Generate header using reflection 

      XElement workbook = new XElement(mainNamespace + "Workbook", 
       new XAttribute(XNamespace.Xmlns + "html", html), 
       new XAttribute(XName.Get("ss", "http://www.w3.org/2000/xmlns/"), ss), 
       new XAttribute(XName.Get("o", "http://www.w3.org/2000/xmlns/"), o), 
       new XAttribute(XName.Get("x", "http://www.w3.org/2000/xmlns/"), x), 
       new XAttribute(XName.Get("xmlns", ""), mainNamespace), 
       new XElement(o + "DocumentProperties", 
         new XAttribute(XName.Get("xmlns", ""), o), 
         new XElement(o + "Author", "Smartdesk Systems Ltd"), 
         new XElement(o + "LastAuthor", "Smartdesk Systems Ltd"), 
         new XElement(o + "Created", DateTime.Now.ToString()) 
        ), //end document properties 
       new XElement(x + "ExcelWorkbook", 
         new XAttribute(XName.Get("xmlns", ""), x), 
         new XElement(x + "WindowHeight", 12750), 
         new XElement(x + "WindowWidth", 24855), 
         new XElement(x + "WindowTopX", 240), 
         new XElement(x + "WindowTopY", 75), 
         new XElement(x + "ProtectStructure", "False"), 
         new XElement(x + "ProtectWindows", "False") 
        ), //end ExcelWorkbook 
       new XElement(mainNamespace + "Styles", 
         new XElement(mainNamespace + "Style", 
          new XAttribute(ss + "ID", "Default"), 
          new XAttribute(ss + "Name", "Normal"), 
          new XElement(mainNamespace + "Alignment", 
           new XAttribute(ss + "Vertical", "Bottom") 
          ), 
          new XElement(mainNamespace + "Borders"), 
          new XElement(mainNamespace + "Font", 
           new XAttribute(ss + "FontName", "Calibri"), 
           new XAttribute(x + "Family", "Swiss"), 
           new XAttribute(ss + "Size", "11"), 
           new XAttribute(ss + "Color", "#000000") 
          ), 
          new XElement(mainNamespace + "Interior"), 
          new XElement(mainNamespace + "NumberFormat"), 
          new XElement(mainNamespace + "Protection") 
         ), 
         new XElement(mainNamespace + "Style", 
          new XAttribute(ss + "ID", "Header"), 
          new XElement(mainNamespace + "Font", 
           new XAttribute(ss + "FontName", "Calibri"), 
           new XAttribute(x + "Family", "Swiss"), 
           new XAttribute(ss + "Size", "11"), 
           new XAttribute(ss + "Color", "#000000"), 
           new XAttribute(ss + "Bold", "1") 
          ) 
         ) 
        ), // close styles 
        new XElement(mainNamespace + "Worksheet", 
         new XAttribute(ss + "Name", sheetName /* Sheet name */), 
         new XElement(mainNamespace + "Table", 
          new XAttribute(ss + "ExpandedColumnCount", headerRow.Count()), 
          new XAttribute(ss + "ExpandedRowCount", rows.Count() + 1), 
          new XAttribute(x + "FullColumns", 1), 
          new XAttribute(x + "FullRows", 1), 
          new XAttribute(ss + "DefaultRowHeight", 15), 
          new XElement(mainNamespace + "Column", 
           new XAttribute(ss + "Width", 81) 
          ), 
          new XElement(mainNamespace + "Row", new XAttribute(ss + "StyleID", "Header"), headerRow), 
          from contentRow in rows 
          select new XElement(mainNamespace + "Row", 
           new XAttribute(ss + "StyleID", "Default"), 
            from p in contentRow.GetType().GetProperties() 
            select new XElement(mainNamespace + "Cell", 
             new XElement(mainNamespace + "Data", new XAttribute(ss + "Type", "String"), p.GetValue(contentRow, null))) /* Build cells using reflection */) 
         ), //close table 
         new XElement(x + "WorksheetOptions", 
          new XAttribute(XName.Get("xmlns", ""), x), 
          new XElement(x + "PageSetup", 
           new XElement(x + "Header", 
            new XAttribute(x + "Margin", "0.3") 
           ), 
           new XElement(x + "Footer", 
            new XAttribute(x + "Margin", "0.3") 
           ), 
           new XElement(x + "PageMargins", 
            new XAttribute(x + "Bottom", "0.75"), 
            new XAttribute(x + "Left", "0.7"), 
            new XAttribute(x + "Right", "0.7"), 
            new XAttribute(x + "Top", "0.75") 
           ) 
          ), 
          new XElement(x + "Print", 
           new XElement(x + "ValidPrinterInfo"), 
           new XElement(x + "HorizontalResolution", 600), 
           new XElement(x + "VerticalResolution", 600) 
          ), 
          new XElement(x + "Selected"), 
          new XElement(x + "Panes", 
           new XElement(x + "Pane", 
            new XElement(x + "Number", 3), 
            new XElement(x + "ActiveRow", 1), 
            new XElement(x + "ActiveCol", 0) 
           ) 
          ), 
          new XElement(x + "ProtectObjects", "False"), 
          new XElement(x + "ProtectScenarios", "False") 
         ) // close worksheet options 
        ) // close Worksheet 
       ); 

      xdoc.Add(workbook); 

      return xdoc; 
     } 
    } 
} 

! XML

에 LINQ와 엑셀 XML에

+1

OutOfMemoryException 예외를 일으키는 .ToString() 대신 MemoryStream 개체를 사용하도록 ToDownloadableXmlFileForExcel2003() 확장 메서드를 업데이트했습니다. XML XLS 문서를 생성하는 방법 중 하나는 파일 크기입니다. 작은 문서는 괜찮지 만 100k + 라인이있는 큰 xls 시트는 아닙니다. – bounav

+2

멋지므로 시도했지만 오류가 발생합니다 "파일 형식이나 파일 확장자가 유효하지 않아 Excel에서 'newexcelfil2.xlsx'파일을 열 수 없습니다. 파일이 손상되지 않았고 파일 확장자가 파일 형식. " 나는 XML이 잘 형성되었음을 확인했다. – tjp69

1

쓰기는 외부 라이브러리를 필요로하지 않으며, 놀라 울 정도로 간단하고, 워크 시트에 어떤을 IEnumerable을 설정하는 반사를 사용! 내가 찾은

: - 저자, 스캇 세인트 존 (그는 자신의 사이트에있는 모든 바이오 정보가없는 나는 그의 URL에서이 추측하고있어)에 의해 설명 된 바와 같이

http://scottstjohn.wordpress.com/2011/04/02/write-to-excel-xml-with-linq-to-xml/

어느 좋은 IEnumerable을 엑셀 XML 스프레드 시트에 쓰는 정말 멋진 확장 클래스. bounav가 Linq를 사용하여 Excel에 작성하는 C#을 참조하십시오. 나는 을 새로운 워크 시트로 추가 할 수 있기를 원했기 때문에 몇 가지 수정을했다. 아래 예제 및 소스 코드를 참조하십시오.

LINQPad의 MyExtensions에 코드를 복사/붙여 넣기하고 바로 사용했습니다.

관련 문제