[英]Export SQL query data to Excel
我有一個查詢,它返回一個非常大的數據集。 我無法像往常一樣將其復制並粘貼到 Excel 中。 我一直在研究如何直接導出到 Excel 工作表。 我在運行 Microsoft Server 2003 的服務器上運行 SQL SERVER 2008。我正在嘗試使用 Microsoft.Jet.OLEDB.4.0 數據提供程序和 Excel 2007。我拼湊了一小段代碼,看起來像這樣已經在例子中看到了。
INSERT INTO OPENDATASOURCE('Microsoft.Jet.OLEDB.4.0',
'Data Source=C:\Working\Book1.xlsx;Extended Properties=EXCEL 12.0;HDR=YES')
SELECT productid, price FROM dbo.product
但是這不起作用,我收到一條錯誤消息說
“關鍵字'SELECT'附近的語法不正確”。
有沒有人對如何做到這一點或可能有更好的方法有任何想法?
我不知道這是否是您要找的,但您可以像這樣將結果導出到 Excel:
在結果窗格中,單擊左上角的單元格以突出顯示所有記錄,然后右鍵單擊左上角的單元格並單擊“結果另存為”。 導出選項之一是 CSV。
你也可以試一試:
INSERT INTO OPENROWSET
('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\Test.xls;','SELECT productid, price FROM dbo.product')
最后,您可以考慮使用 SSIS(取代 DTS)進行數據導出。 這是一個教程的鏈接:
http://www.accelebrate.com/sql_training/ssis_2008_tutorial.htm
== 更新 #1 ==
要將結果保存為帶有列標題的 CSV 文件,可以按照以下步驟操作:
如果您只是需要導出到 excel,則可以使用導出數據向導。 右鍵單擊數據庫,任務-> 導出數據。
我有一個類似的問題,但有一個轉折 - 當結果集來自一個查詢時,上面列出的解決方案有效,但在我的情況下,我有多個單獨的選擇查詢,我需要將結果導出到 Excel。 下面只是一個例子來說明,雖然我可以name in
子句中做一個name in
......
select a,b from Table_A where name = 'x'
select a,b from Table_A where name = 'y'
select a,b from Table_A where name = 'z'
該向導讓我將一個查詢的結果導出到 excel,但在這種情況下,不是所有不同查詢的結果。
當我研究時,我發現我們可以禁用網格的結果並啟用文本的結果。 因此,按 Ctrl + T,然后執行所有語句。 這應該在輸出窗口中將結果顯示為文本文件。 您可以將文本處理為制表符分隔的格式,以便導入 Excel。
您還可以按 Ctrl + Shift + F 將結果導出到文件 - 它導出為 .rpt 文件,可以使用文本編輯器打開該文件並進行操作以進行 excel 導入。
希望這可以幫助任何其他有類似問題的人。
對於來這里尋找如何在 C# 中執行此操作的任何人,我嘗試了以下方法並在dotnet core 2.0.3
和entity framework core 2.0.3
取得了成功
首先創建您的模型類。
public class User
{
public string Name { get; set; }
public int Address { get; set; }
public int ZIP { get; set; }
public string Gender { get; set; }
}
然后安裝EPPlus Nuget 包。 (我使用的是 4.0.5 版,可能也適用於其他版本。)
Install-Package EPPlus -Version 4.0.5
創建ExcelExportHelper
類,該類將包含將數據集轉換為 Excel 行的邏輯。 此類與您的模型類或數據集沒有依賴關系。
public class ExcelExportHelper
{
public static string ExcelContentType
{
get
{ return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; }
}
public static DataTable ListToDataTable<T>(List<T> data)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
DataTable dataTable = new DataTable();
for (int i = 0; i < properties.Count; i++)
{
PropertyDescriptor property = properties[i];
dataTable.Columns.Add(property.Name, Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType);
}
object[] values = new object[properties.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = properties[i].GetValue(item);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
public static byte[] ExportExcel(DataTable dataTable, string heading = "", bool showSrNo = false, params string[] columnsToTake)
{
byte[] result = null;
using (ExcelPackage package = new ExcelPackage())
{
ExcelWorksheet workSheet = package.Workbook.Worksheets.Add(String.Format("{0} Data", heading));
int startRowFrom = String.IsNullOrEmpty(heading) ? 1 : 3;
if (showSrNo)
{
DataColumn dataColumn = dataTable.Columns.Add("#", typeof(int));
dataColumn.SetOrdinal(0);
int index = 1;
foreach (DataRow item in dataTable.Rows)
{
item[0] = index;
index++;
}
}
// add the content into the Excel file
workSheet.Cells["A" + startRowFrom].LoadFromDataTable(dataTable, true);
// autofit width of cells with small content
int columnIndex = 1;
foreach (DataColumn column in dataTable.Columns)
{
int maxLength;
ExcelRange columnCells = workSheet.Cells[workSheet.Dimension.Start.Row, columnIndex, workSheet.Dimension.End.Row, columnIndex];
try
{
maxLength = columnCells.Max(cell => cell.Value.ToString().Count());
}
catch (Exception) //nishanc
{
maxLength = columnCells.Max(cell => (cell.Value +"").ToString().Length);
}
//workSheet.Column(columnIndex).AutoFit();
if (maxLength < 150)
{
//workSheet.Column(columnIndex).AutoFit();
}
columnIndex++;
}
// format header - bold, yellow on black
using (ExcelRange r = workSheet.Cells[startRowFrom, 1, startRowFrom, dataTable.Columns.Count])
{
r.Style.Font.Color.SetColor(System.Drawing.Color.White);
r.Style.Font.Bold = true;
r.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
r.Style.Fill.BackgroundColor.SetColor(Color.Brown);
}
// format cells - add borders
using (ExcelRange r = workSheet.Cells[startRowFrom + 1, 1, startRowFrom + dataTable.Rows.Count, dataTable.Columns.Count])
{
r.Style.Border.Top.Style = ExcelBorderStyle.Thin;
r.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
r.Style.Border.Left.Style = ExcelBorderStyle.Thin;
r.Style.Border.Right.Style = ExcelBorderStyle.Thin;
r.Style.Border.Top.Color.SetColor(System.Drawing.Color.Black);
r.Style.Border.Bottom.Color.SetColor(System.Drawing.Color.Black);
r.Style.Border.Left.Color.SetColor(System.Drawing.Color.Black);
r.Style.Border.Right.Color.SetColor(System.Drawing.Color.Black);
}
// removed ignored columns
for (int i = dataTable.Columns.Count - 1; i >= 0; i--)
{
if (i == 0 && showSrNo)
{
continue;
}
if (!columnsToTake.Contains(dataTable.Columns[i].ColumnName))
{
workSheet.DeleteColumn(i + 1);
}
}
if (!String.IsNullOrEmpty(heading))
{
workSheet.Cells["A1"].Value = heading;
// workSheet.Cells["A1"].Style.Font.Size = 20;
workSheet.InsertColumn(1, 1);
workSheet.InsertRow(1, 1);
workSheet.Column(1).Width = 10;
}
result = package.GetAsByteArray();
}
return result;
}
public static byte[] ExportExcel<T>(List<T> data, string Heading = "", bool showSlno = false, params string[] ColumnsToTake)
{
return ExportExcel(ListToDataTable<T>(data), Heading, showSlno, ColumnsToTake);
}
}
現在在你想要生成excel文件的地方添加這個方法,可能是控制器中的一個方法。 您也可以為存儲過程傳遞參數。 請注意,該方法的返回類型是FileContentResult
。 無論您執行什么查詢,重要的是您必須將結果保存在List
。
[HttpPost]
public async Task<FileContentResult> Create([Bind("Id,StartDate,EndDate")] GetReport getReport)
{
DateTime startDate = getReport.StartDate;
DateTime endDate = getReport.EndDate;
// call the stored procedure and store dataset in a List.
List<User> users = _context.Reports.FromSql("exec dbo.SP_GetEmpReport @start={0}, @end={1}", startDate, endDate).ToList();
//set custome column names
string[] columns = { "Name", "Address", "ZIP", "Gender"};
byte[] filecontent = ExcelExportHelper.ExportExcel(users, "Users", true, columns);
// set file name.
return File(filecontent, ExcelExportHelper.ExcelContentType, "Report.xlsx");
}
可以在此處找到更多詳細信息
我看到您正在嘗試將 SQL 數據導出到 Excel,以避免將非常大的數據集復制粘貼到 Excel 中。
您可能有興趣了解如何將 SQL 數據導出到 Excel 並自動更新導出(使用任何 SQL 數據庫:MySQL、Microsoft SQL Server、PostgreSQL)。

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.