[英]How can I only get visible cells in an Excel spreadsheet using OpenXML?
[英]How can I write to an Excel spreadsheet using Linq?
我正在編寫一個應用程序,我需要從數據庫中檢索一些行並將它們轉儲到Excel電子表格中。 我正在使用Linq來檢索這些行。
是否可以將這些行直接轉儲到Excel工作表中的對應部分(其中Excel中的一個單元格對應於數據庫中的一個單元格)?
我本人並不是使用庫來做這些事情的忠實粉絲,因為我總是發現它在某些時候會受到限制......
我使用反射來生成列標題並獲取每行的單元格值。 如果您使用的是.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;
}
}
}
我還創建了另一種擴展方法,以便在Web場景中輕松返回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;
}
希望這可以幫助!
沒有直接的方法來連接這兩個。 聽起來你想要LINQ to SQL來處理查詢生成,而不是O / R映射(因為Excel不知道如何處理來自LINQ的對象 - 它們看起來不再像數據行了)。 您可以通過調用(datacontext).GetCommand(yourLinqQueryHere),然后在SqlCommand中將其作為CommandText運行來完成第一部分。 調用ExecuteReader(),然后調用GetSchemaTable()來確定列的順序。 然后(假設您正在自動化Excel)將(DbDataReader).GetValues()的結果傳遞給Excel(工作表).Row [x] .Values並且它會將結果顯示出來。您可能需要重新排序內容。 如果您沒有自動化Excel,則需要使用帶有OleDbConnection的Excel的OLED OLEDB提供程序轉儲值,或使用第三方組件生成電子表格。
您可以:
看一下這個Excel數據對象提供程序 。 我沒有親自使用它的寫入功能,我調整了閱讀支持以允許有序(以及命名)列標識符,但它可能是朝着正確方向邁出的一步。 請記住,除非在目標計算機上安裝了Excel 2003+,否則無法寫入或讀取XLSX文件; 標准的XLS文件可以在任何Windows機器上使用。
我可以在這里找到帶有序數列的改編版本。 如果您決定使用該代碼,您可能會發現在當前版本(在上面的鏈接中)實現它是必要/有用的。 我的版本是2.0和2.5版本的混合功能 - 它具有所有閱讀功能(有2.5次升級),但沒有寫作。 哦 - 與版本2.0或2.5不同,我的版本不要求Excel文檔中的第一個工作表命名為“Sheet1”。
希望有所幫助!
最快的解決方案是創建一個csv文件:
col1, colb, colc
col1, colb, colc
Excel與csv文件配合得很好。
您使用LINQ檢索數據的事實是無關緊要的。 你真正想要的是一個編寫Excel的好庫。 完成后,您可以簡單地遍歷結果以在Excel工作表中創建行。
就圖書館而言,我使用的是NPOI ,它一直很棒。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.