2009-10-06 17 views
9

私はDBからいくつかの行を取得し、Excelスプレッドシートにそれらをダンプする必要があるアプリケーションを書いています。私はこれらの行を取得するためにLinqを使用しています。Linqを使用してExcelスプレッドシートに書き込むにはどうすればよいですか?

これらの行をExcelシートの対応する部分に直接ダンプすることはできますか(Excelの1つのセルがDBの1つのセルに対応します)。

答えて

5

これら2つを直接接続する方法はありません。これは、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 

Excelは、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ファイルにエクスポートできます。ここで

は、私はそれをやった方法です:

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; 
     } 
    } 
} 

私はまた、ウェブのシナリオで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; 
} 

・ホープ、このことができます! XML

にLINQのExcel XMLへ

+1

OutOfMemoryException例外を引き起こしていた.ToString()の代わりにMemoryStreamオブジェクトを使用するようにToDownloadableXmlFileForExcel2003()拡張メソッドを更新しました。 XML XLSドキュメントを生成する私のやり方の1つの問題は、ファイルのサイズです。小さな文書の場合は問題ありませんが、大きなxlsシートの場合は100k +行ありません。 – bounav

+2

これはうまく見えましたが、私は試しましたが、エラーが発生します。 "ファイルのフォーマットやファイルの拡張子が無効であるため、Excel 'newexcelfil2.xlsx'ファイルを開くことができません。ファイルの形式を指定します。私はXMLがうまく形成されていることを確認しました。 – tjp69

1

書き込みは、外部ライブラリを必要としない、驚くほど簡単で、ワークシートに任意のIEnumerableをを回すためにリフレクションを使用しています!

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

著者、スコット・セント・ジョン(私は彼のURLからこれを推測している - 彼は自分のサイト上の任意のバイオ情報を持っていない)で説明したように:私が見つけ

Excel XMLスプレッドシートにIEnumerableを書き込むための本当に素晴らしい拡張クラスです。 bounavによってLinqを使ってExcelに書き込むC#を参照してください。新しい IEnumerablesをワークシートとして追加できるようにするために、私は をいくつか変更しました。以下の例とそのソースコードを参照

LINQPadのMyExtensionsにコードをコピーして貼り付け、すぐに使用しました。

関連する問題