关于数据导入与导出
现在我想实现数据在datagridview与execl之间导入与导出,请问怎么写代码?
重点:如何定位datagridview中的单元格并获得值;
我的思路:想用类似for each row as datagridviewrow in datagridview.rows来做循环
[解决办法]
public void ExportToExcel(DataSet ds)// DataSet ds=(DataSet)datagriveiw1.DataSource();
{
if(ds.Tables.Count!=0)
{
string tempFileName = GetTempFileName();
object filename =你要写入的excel的fullname;
object Nothing = System.Reflection.Missing.Value;
Excel.Application myExcel = new Excel.ApplicationClass();
myExcel.Application.Workbooks.Add(Nothing);
try
{
int totalCount = 0;
for(int k =0;k <ds.Tables.Count;k++)
{
int row = ds.Tables[k].Rows.Count;
int column = ds.Tables[k].Columns.Count;
for(int i = 0;i <column;i++)
{
myExcel.Cells[totalCount+2,1+i] = ds.Tables[k].Columns[i].ColumnName;
}
for(int i = 0;i <row;i++)
{
for(int j =0;j <column;j++)
{
myExcel.Cells[totalCount+3+i,1+j] = " ' " + ds.Tables[k].Rows[i][j].ToString();
}
}
totalCount = totalCount + row +4;
}
try
{
myExcel.ActiveWorkbook._SaveAs(filename,Nothing,Nothing,Nothing,Nothing,Nothing,XlSaveAsAccessMode.xlExclusive,Nothing,Nothing,Nothing,Nothing);
}
catch
{
System.Windows.Forms.MessageBox.Show( "系统找不到指定目录下的文件: "+filename);
return;
}
myExcel.Visible = true;
}
catch(Exception e)
{
System.Windows.Forms.MessageBox.Show( "wrong " + e.Message);
}
}
else
{
System.Windows.Forms.MessageBox.Show( "No Data ");
}
}
[解决办法]
楼主可以到下面的博克上看看
http://jens.blogbus.com/s30527/index_3.html