用C#编程的时候,导出到excel表的时候,提示"警告 1方法“Excel._Worksheet.Activate()”和非方法“Excel.DocEvents_Event.Activate”之间存在二义性。将使用方法组."不知道怎么解决.已问过很多人.部分代码:
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlBook = xlApp.Workbooks.Add(DBControl.DestinationFileName);
Excel.Worksheet xlSheet = (Excel.Worksheet)xlBook.Worksheets["港口代码"];
xlSheet.Activate(); xlSheet.Application.Visible = true;
//列标题
for (int j = 1; j <= this.c1TrueDBGrid1.Columns.Count; j++)
{
xlSheet.Cells[3, j] = this.c1TrueDBGrid1.Columns[j-1].Caption;
}
//打印表体
for (int i = 0; i <= myDs.Tables[0].Rows.Count - 1; i++)
{
for (int j = 1; j <= this.c1TrueDBGrid1.Columns.Count; j++)
{
xlSheet.Cells[4 + i, j] = "'" + myDs.Tables[0].Rows[i][j-1];
}
}
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlBook = xlApp.Workbooks.Add(DBControl.DestinationFileName);
Excel.Worksheet xlSheet = (Excel.Worksheet)xlBook.Worksheets["港口代码"];
xlSheet.Activate(); xlSheet.Application.Visible = true;
//列标题
for (int j = 1; j <= this.c1TrueDBGrid1.Columns.Count; j++)
{
xlSheet.Cells[3, j] = this.c1TrueDBGrid1.Columns[j-1].Caption;
}
//打印表体
for (int i = 0; i <= myDs.Tables[0].Rows.Count - 1; i++)
{
for (int j = 1; j <= this.c1TrueDBGrid1.Columns.Count; j++)
{
xlSheet.Cells[4 + i, j] = "'" + myDs.Tables[0].Rows[i][j-1];
}
}
我这个方法,没有错 private void button3_Click(object sender, System.EventArgs e)
{//导出excel
doExport(ds,"未知名文档");
}
private void doExport(DataSet ds,string strExcelFileName)
{ //导出execl
try
{
Excel.Application excel= new Excel.Application();
int rowIndex=1;
int colIndex=0;
excel.Application.Workbooks.Add(true);
System.Data.DataTable table=ds.Tables[0] ;
foreach(DataColumn col in table.Columns)
{
colIndex++;
excel.Cells[1,colIndex]=col.ColumnName;
}
foreach(DataRow row in table.Rows)
{
rowIndex++;
colIndex=0;
foreach(DataColumn col in table.Columns)
{
colIndex++;
excel.Cells[rowIndex,colIndex]=row[col.ColumnName].ToString();
}
}
excel.Visible=false;
excel.Save(strExcelFileName);
excel.Quit();
excel=null;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message,"警告!!!",MessageBoxButtons.OK,MessageBoxIcon.Stop);
}
GC.Collect();//垃圾回收
}
Excel._Workbook xlBook = xlApp.Workbooks.Add(DBControl.DestinationFileName);
Excel.Worksheet xlSheet = (Excel._Worksheet)xlBook.Worksheets["港口代码"];
xlSheet.Activate();
......