gpt4 book ai didi

c# - 将 SQL 导出到 Excel

转载 作者:太空狗 更新时间:2023-10-29 19:57:24 25 4
gpt4 key购买 nike

如何将我的数据从 SQL Server 2008 导出到 Excel 2010 或更高版本?

我试过SQL方式:

sp_configure 'show advanced options', 0;
GO
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 0;
GO
RECONFIGURE;
GO
INSERT INTO OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=C:\testing.xls;Extended Properties=EXCEL 12.0;HDR=YES',
'SELECT NO_ORDRE, Date FROM [Sheet1$]')
SELECT [NO_ORDRE], GETDATE() FROM ORDRE
GO

不幸的是我收到错误:OLE DB 提供程序“Microsoft.Jet.OLEDB.4.0”不能用于分布式查询,因为该提供程序配置为在 STA 模式下运行。

然后我尝试了 C# 方式:

 public class ExportToExcel
{
private Excel.Application app;

private Excel.Workbook workbook;
private Excel.Worksheet previousWorksheet;
// private Excel.Range workSheet_range;
private string folder;

public ExportToExcel(string folder)
{

this.folder = folder;
this.app = null;
this.workbook = null;
this.previousWorksheet = null;
// this.workSheet_range = null;

createDoc();
}

private void createDoc()
{
try
{
app = new Excel.Application();
app.Visible = false;
workbook = app.Workbooks.Add(1);
}
catch (Exception excThrown)
{
throw new Exception(excThrown.Message);
}
finally
{
}
}

public void shutDown()
{
try
{
workbook = null;
app.Quit();
}
catch (Exception excThrown)
{
throw new Exception(excThrown.Message);
}
finally
{
}
}

public void ExportTable(string query, string sheetName)
{
SqlDataReader myReader = null;
try
{
using (var connectionWrapper = new Connexion())
{
var connectedConnection = connectionWrapper.GetConnected();
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Sheets.Add(Missing.Value, Missing.Value, 1, Excel.XlSheetType.xlWorksheet);

worksheet.Name = sheetName;
previousWorksheet = worksheet;

SqlCommand myCommand = new SqlCommand(query, connectionWrapper.conn);

myReader = myCommand.ExecuteReader();

int columnCount = myReader.FieldCount;

for (int n = 0; n < columnCount; n++)
{
//Console.Write(myReader.GetName(n) + "\t");
createHeaders(worksheet, 1, n + 1, myReader.GetName(n));
}

int rowCounter = 2;
while (myReader.Read())
{
for (int n = 0; n < columnCount; n++)
{
//Console.WriteLine();
//Console.Write(myReader[myReader.GetName(n)].ToString() + "\t");
addData(worksheet, rowCounter, n + 1, myReader[myReader.GetName(n)].ToString());
}
rowCounter++;
}

}
}

catch (Exception e)
{
Console.WriteLine(e.ToString());

}
finally
{
if (myReader != null && !myReader.IsClosed)
{
myReader.Close();
}
myReader = null;
}

}

public void createHeaders(Excel.Worksheet worksheet, int row, int col, string htext)
{
worksheet.Cells[row, col] = htext;
}

public void addData(Excel.Worksheet worksheet, int row, int col, string data)
{
worksheet.Cells[row, col] = data;
}

public void SaveWorkbook()
{

String folderPath = "C:\\My Files\\" + this.folder;

if (!System.IO.Directory.Exists(folderPath))
{
System.IO.Directory.CreateDirectory(folderPath);
}

string fileNameBase = "db";
String fileName = fileNameBase;
string ext = ".xlsx";
int counter = 1;

while (System.IO.File.Exists(folderPath + fileName + ext))
{
fileName = fileNameBase + counter;
counter++;
}

fileName = fileName + ext;

string filePath = folderPath + fileName;

try
{
workbook.SaveAs(filePath, Excel.XlFileFormat.xlWorkbookDefault, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);

}
catch (Exception e)
{
Console.WriteLine(e.ToString());

}
}



}

不幸的是我得到了错误:由于以下错误,检索 CLSID 为 {00024500-0000-0000-C000-000000000046} 的组件的 COM 类工厂失败:80070005 访问被拒绝。 (HRESULT 异常:0x80070005 (E_ACCESSDENIED))。

知道如何将 SQL 导出到 Excel 吗?

最佳答案

您最好的选择可能是将其写成 CSV。 Excel 将自己注册为 CSV 文件的文件处理程序,因此默认情况下它将在 excel 中打开。

例如:

private void SQLToCSV(string query, string Filename)
{

SqlConnection conn = new SqlConnection(connection);
conn.Open();
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataReader dr = cmd.ExecuteReader();

using (System.IO.StreamWriter fs = new System.IO.StreamWriter(Filename))
{
// Loop through the fields and add headers
for (int i = 0; i < dr.FieldCount; i++)
{
string name = dr.GetName(i);
if (name.Contains(","))
name = "\"" + name + "\"";

fs.Write(name + ",");
}
fs.WriteLine();

// Loop through the rows and output the data
while (dr.Read())
{
for (int i = 0; i < dr.FieldCount; i++)
{
string value = dr[i].ToString();
if (value.Contains(","))
value = "\"" + value + "\"";

fs.Write(value + ",");
}
fs.WriteLine();
}

fs.Close();
}
}

关于c# - 将 SQL 导出到 Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8580591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com