我使用這些連接字符串,根據文件的擴展名:數據導出到Excel文件2003年,2007年及以上
爲2003:Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties='Excel 8.0;
爲2007:Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties='Excel 12.0;
這裏是獲得連接。
string con_excel = "";
switch (Extension.ToLower())
{
case ".xls":
con_excel = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
break;
case ".xlsx":
con_excel = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
break;
}
con_excel = con_excel.Replace("filename", filePath);
以下是生成excel文件的代碼。
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
oXL = new Excel.Application();
oXL.Visible = false;
oXL.SheetsInNewWorkbook = 1;
oWB = (Excel._Workbook)(oXL.Workbooks.Add());
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
try
{
string[] colNames = new string[dataTable.Columns.Count];
int col = 0;
foreach (DataColumn dc in dataTable.Columns)
colNames[col++] = dc.ColumnName;
char lastColumn = (char)(65 + dataTable.Columns.Count - 1);
oSheet.get_Range("A1", lastColumn + "1").Value2 = colNames;
oSheet.get_Range("A1", lastColumn + "1").Font.Bold = true;
oSheet.get_Range("A1", lastColumn + "1").VerticalAlignment = Excel.XlVAlign.xlVAlignCenter;
DataRow[] dr = dataTable.Select();
string[,] rowData = new string[dr.Count<DataRow>(), dataTable.Columns.Count + 1];
int rowCnt = 0;
foreach (DataRow row in dr)
{
for (col = 0; col < dataTable.Columns.Count; col++)
{
rowData[rowCnt, col] = row[col].ToString();
}
rowCnt++;
}
rowCnt++;
oSheet.get_Range("A2", lastColumn + rowCnt.ToString()).Value = rowData;
oXL.Visible = false;
oXL.UserControl = true;
String sNewFolderName = "Report_" + intReportId;
filename = Server.MapPath("Your Report\\" + sNewFolderName + DateTime.Now.ToString("dd-MM-yyyy_hh-mm-ss") + Extension);
oSheet.SaveAs(filename);
System.Runtime.InteropServices.Marshal.ReleaseComObject(oWB);
oXL.Quit();
Marshal.ReleaseComObject(oSheet);
Marshal.ReleaseComObject(oWB);
Marshal.ReleaseComObject(oXL);
oSheet = null;
oWB = null;
oXL = null;
GC.GetTotalMemory(false);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.GetTotalMemory(true);
//The excel is created and opened for insert value. We most close this excel using this system
Process[] localByName = Process.GetProcessesByName("EXCEL");
foreach (Process process in localByName)
{
process.Kill();
}
2007文件格式沒問題。
我試着上傳了2003年(的.xls)Excel文件,然後還產生2003(.xls)格式。但是當我打開該文件時,出現以下錯誤。
文件你想在非指定的文件擴展名不同的格式打開「FileName.xls」。在打開文件之前,驗證該文件是否已損壞並且來自受信任的來源。你想現在打開文件嗎?
是連接字符串這一點,因爲?
你的連接字符串是不完整的。未封閉的報價? – Raptor