[英]Export SQL query data to Excel
I have a query that returns a very large data set.我有一个查询,它返回一个非常大的数据集。 I cannot copy and paste it into Excel which I usually do.
我无法像往常一样将其复制并粘贴到 Excel 中。 I have been doing some research on how to export directly to an Excel sheet.
我一直在研究如何直接导出到 Excel 工作表。 I am running SQL SERVER 2008 on a server running Microsoft Server 2003. I am trying to use the Microsoft.Jet.OLEDB.4.0 data provider and Excel 2007. I've pieced together a small piece of code that looks like this from what I've seen in examples.
我在运行 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
However this is not working, I am getting an error message saying但是这不起作用,我收到一条错误消息说
"Incorrect syntax near the keyword 'SELECT'".
“关键字'SELECT'附近的语法不正确”。
Does anyone have any ideas about how to do this or possibly a better approach?有没有人对如何做到这一点或可能有更好的方法有任何想法?
I don't know if this is what you're looking for, but you can export the results to Excel like this:我不知道这是否是您要找的,但您可以像这样将结果导出到 Excel:
In the results pane, click the top-left cell to highlight all the records, and then right-click the top-left cell and click "Save Results As".在结果窗格中,单击左上角的单元格以突出显示所有记录,然后右键单击左上角的单元格并单击“结果另存为”。 One of the export options is CSV.
导出选项之一是 CSV。
You might give this a shot too:你也可以试一试:
INSERT INTO OPENROWSET
('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\Test.xls;','SELECT productid, price FROM dbo.product')
Lastly, you can look into using SSIS (replaced DTS) for data exports.最后,您可以考虑使用 SSIS(取代 DTS)进行数据导出。 Here is a link to a tutorial:
这是一个教程的链接:
http://www.accelebrate.com/sql_training/ssis_2008_tutorial.htm http://www.accelebrate.com/sql_training/ssis_2008_tutorial.htm
== Update #1 == == 更新 #1 ==
To save the result as CSV file with column headers, one can follow the steps shown below:要将结果保存为带有列标题的 CSV 文件,可以按照以下步骤操作:
If you're just needing to export to excel, you can use the export data wizard.如果您只是需要导出到 excel,则可以使用导出数据向导。 Right click the database, Tasks->Export data.
右键单击数据库,任务-> 导出数据。
I had a similar problem but with a twist - the solutions listed above worked when the resultset was from one query but in my situation, I had multiple individual select queries for which I needed results to be exported to Excel.我有一个类似的问题,但有一个转折 - 当结果集来自一个查询时,上面列出的解决方案有效,但在我的情况下,我有多个单独的选择查询,我需要将结果导出到 Excel。 Below is just an example to illustrate although I could do a
name in
clause...下面只是一个例子来说明,虽然我可以
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'
The wizard was letting me export the result from one query to excel but not all results from different queries in this case.该向导让我将一个查询的结果导出到 excel,但在这种情况下,不是所有不同查询的结果。
When I researched, I found that we could disable the results to grid and enable results to Text.当我研究时,我发现我们可以禁用网格的结果并启用文本的结果。 So, press Ctrl + T, then execute all the statements.
因此,按 Ctrl + T,然后执行所有语句。 This should show the results as a text file in the output window.
这应该在输出窗口中将结果显示为文本文件。 You can manipulate the text into a tab delimited format for you to import into Excel.
您可以将文本处理为制表符分隔的格式,以便导入 Excel。
You could also press Ctrl + Shift + F to export the results to a file - it exports as a .rpt file that can be opened using a text editor and manipulated for excel import.您还可以按 Ctrl + Shift + F 将结果导出到文件 - 它导出为 .rpt 文件,可以使用文本编辑器打开该文件并进行操作以进行 excel 导入。
Hope this helps any others having a similar issue.希望这可以帮助任何其他有类似问题的人。
For anyone coming here looking for how to do this in C# , I have tried the following method and had success in dotnet core 2.0.3
and entity framework core 2.0.3
对于来这里寻找如何在 C# 中执行此操作的任何人,我尝试了以下方法并在
dotnet core 2.0.3
和entity framework core 2.0.3
取得了成功
First create your model class.首先创建您的模型类。
public class User
{
public string Name { get; set; }
public int Address { get; set; }
public int ZIP { get; set; }
public string Gender { get; set; }
}
Then install EPPlus Nuget package .然后安装EPPlus Nuget 包。 (I used version 4.0.5, probably will work for other versions as well.)
(我使用的是 4.0.5 版,可能也适用于其他版本。)
Install-Package EPPlus -Version 4.0.5
The create ExcelExportHelper
class, which will contain the logic to convert dataset to Excel rows.创建
ExcelExportHelper
类,该类将包含将数据集转换为 Excel 行的逻辑。 This class do not have dependencies with your model class or dataset.此类与您的模型类或数据集没有依赖关系。
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);
}
}
Now add this method where you want to generate the excel file, probably for a method in the controller.现在在你想要生成excel文件的地方添加这个方法,可能是控制器中的一个方法。 You can pass parameters for your stored procedure as well.
您也可以为存储过程传递参数。 Note that the return type of the method is
FileContentResult
.请注意,该方法的返回类型是
FileContentResult
。 Whatever query you execute, important thing is you must have the results in a List
.无论您执行什么查询,重要的是您必须将结果保存在
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");
}
I see that you're trying to export SQL data to Excel to avoid copy-pasting your very large data set into Excel.我看到您正在尝试将 SQL 数据导出到 Excel,以避免将非常大的数据集复制粘贴到 Excel 中。
You might be interested in learning how to export SQL data to Excel and update the export automatically (with any SQL database: MySQL, Microsoft SQL Server, PostgreSQL).您可能有兴趣了解如何将 SQL 数据导出到 Excel 并自动更新导出(使用任何 SQL 数据库:MySQL、Microsoft SQL Server、PostgreSQL)。
 
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.