try
{
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Application.Workbooks.Add(true);
if (ds.Tables.Contains("viewPigSlice") && ds.Tables["viewPigSlice"].Rows.Count > 0)
{
//生成字段
for(int i=0;i<dgvViewPigSliceInfo.Columns.Count;i++)
{
excel.Cells[1, i + 1] = dgvViewPigSliceInfo.Columns[i].HeaderCell.Value;
}
//填充数据
for (int i = 0; i < dgvViewPigSliceInfo.Rows.Count; i++)
{
for(int j=0;j<dgvViewPigSliceInfo.Columns.Count;j++)
{
if(dgvViewPigSliceInfo.Rows[i].Cells[j].Value==typeof(string))
{
excel.Cells[i + 2,j + 1] =""+ dgvViewPigSliceInfo.Rows[i].Cells[j].Value.ToString();
}else
{
excel.Cells[i + 2, j + 1] = dgvViewPigSliceInfo.Rows[i].Cells[j].Value.ToString();
}
}
}
excel.Visible = true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}