将SQL查询数据导出到Excel

时间:2011-09-12 14:41:59

标签: sql sql-server excel export-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'附近的语法不正确。”

有没有人对如何做到这一点或可能是更好的方法有任何想法?

5 个答案:

答案 0 :(得分:45)

我不知道这是否是您要找的,但您可以将结果导出到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 :(得分:15)

如果您只需要导出到Excel,则可以使用导出数据向导。 右键单击数据库,任务 - >导出数据。

答案 2 :(得分:1)

我有一个类似的问题,但有一个转折点 - 上面列出的解决方案在结果集来自一个查询时有效,但在我的情况下,我有多个单独的选择查询,我需要将结果导出到Excel。下面只是一个例子来说明,虽然我可以做一个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,但在这种情况下不是来自不同查询的所有结果。

当我研究时,我发现我们可以将结果禁用到网格并将结果启用到Text。因此,按Ctrl + T,然后执行所有语句。这应该在输出窗口中将结果显示为文本文件。您可以将文本操作为制表符分隔格式,以便导入Excel。

您也可以按Ctrl + Shift + F将结果导出到文件 - 它将导出为.rpt文件,可以使用文本编辑器打开并操作excel导入。

希望这有助于其他有类似问题的人。

答案 3 :(得分:0)

对于来这里寻求如何在C#中完成此操作的人,我尝试了以下方法,并在dotnet core 2.0.3entity 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 package。 (我使用的是4.0.5版,可能也适用于其他版本。)

Install-Package EPPlus -Version 4.0.5

create 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"); 
}

更多详细信息,请here

答案 4 :(得分:0)

我发现您正在尝试将SQL数据导出到Excel,以避免将非常大的数据集复制粘贴到Excel中。

您可能有兴趣学习如何将SQL数据导出到Excel并自动更新导出(使用任何SQL数据库:MySQL,Microsoft SQL Server,PostgreSQL)。

要将数据从SQL导出到Excel,您需要执行以下两个步骤:

  • 步骤1:将Excel连接到您的SQL数据库‍(Microsoft SQL Server,MySQL,PostgreSQL ...)
  • 第2步:将SQL数据导入Excel

结果将是您要从SQL数据库查询数据到Excel的表的列表:

步骤1:将Excel连接到外部数据源:您的SQL数据库

  1. 安装ODBC
  2. 安装驱动程序
  3. 避免常见错误
  4. 创建DSN

步骤2:将您的SQL数据导入Excel

  1. 单击您想要数据透视表的位置
  2. 点击插入
  3. 点击数据透视表
  4. 点击“使用外部数据源”,然后选择“连接”
  5. 点击“系统DSN”标签
  6. 选择在ODBC管理器中创建的DSN
  7. 填写请求的用户名和密码
  8. 避免常见错误
  9. 访问“ Microsoft查询”对话框
  10. 单击箭头以查看数据库中的表列表
  11. 选择要从SQL数据库查询数据到Excel的表
  12. 选择完毕后,点击返回数据

要自动更新导出,还有两个附加步骤:

  1. 使用外部SQL数据源创建数据透视表
  2. 使用GETPIVOTDATA函数在Excel中自动执行SQL数据更新

我已经创建了一个step-by-step tutorial整个过程,从将Excel连接到SQL,直到整个过程都自动更新。您可能会发现detailed explanations and screenshots有用。