我正在尝试将数据导出到Excel工作表我已编写代码但收到错误我不知道我错在哪里请帮助
显示错误"无法修改它在只读数据库中的表的设计"
public override void ExportToExcel()
{
MModule objModule = new MModule();
objModule.LoadModule(this.Data.MID);
DatabaseObject objData = new DatabaseObject();
string file = DateTime.Now.Ticks + "_" + objModule.Title + ".xlsx";
System.IO.File.Copy(Server.MapPath("/Excel/Export/template.xlsx"),
Server.MapPath("/Excel/Export/" + file));
string filename = Server.MapPath("/Excel/Export/" + file);
objData.Query = "SELECT * FROM " + objModule.TableName + "";
DataTable dtReport = objData.GetTable();
System.Data.OleDb.OleDbConnection con = new
System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=" + filename + ";Mode=ReadWrite;Extended Properties=\"Excel 12.0
Xml;HDR=YES\"");
con.Open();
System.Data.OleDb.OleDbCommand cmd = con.CreateCommand();
string tableString = "";
string ColString = "";
for (int i = 0; i < dtReport.Columns.Count; i++)
{
tableString += "[" + dtReport.Columns[i].Caption + "] varchar(255),";
ColString += "[" + dtReport.Columns[i].Caption + "],";
}
tableString = tableString.Substring(0, tableString.Length - 1);
try
{
ColString = ColString.Substring(0, ColString.Length - 1);
cmd.CommandText = "CREATE TABLE MySheet (ID char(255), Field1 char(255))";
cmd.ExecuteNonQuery();
string ValString = "";
for (int j = 0; j < dtReport.Rows.Count; j++)
{
ValString = "";
for (int i = 0; i < dtReport.Columns.Count; i++)
{
ValString += "'" + dtReport.Rows[j][i] + "',";
}
ValString = ValString.Substring(0, ValString.Length - 1);
cmd.CommandText = "Insert Into " + objModule.Title + "(" + ColString +
") Values (" + ValString + ");";
cmd.ExecuteNonQuery();
}
cmd.Dispose();
con.Dispose();
con.Close();
Microsoft.Office.Interop.Excel.Application excelApplication = new
Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook workbook =
excelApplication.Workbooks.Open(filename,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
excelApplication.DisplayAlerts = false;
((Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1]).Delete();
workbook.Close(true, filename, null);
excelApplication.DisplayAlerts = true;
}
catch (Exception ex)
{
}
}