日期:2014-05-18 浏览次数:21312 次
using Microsoft.Office.Interop.Excel;
 ApplicationClass excel = new ApplicationClass();
            excel.Application.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
            for (int i = 1; i <= ds.Tables[0].Columns.Count; i++)
            {
                excel.Cells[1, i] = ds.Tables[0].Columns[i - 1].ColumnName.ToString().ToUpper();
            }
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
                {
                    excel.Cells[i + 2, j + 1] = ds.Tables[0].Rows[i][j].ToString();
                }
            }
            excel.Visible = true;
            excel.ScreenUpdating = true;
------解决方案--------------------
		
               private static void ExportToExcel(DataSet ds)
		{
			object oMissing = System.Reflection.Missing.Value;
			Excel.ApplicationClass xlApp = new Excel.ApplicationClass();
			try
			{
				// 打开Excel文件。
				Excel.Workbook xlWorkbook =xlApp.Workbooks.Add(1);
				Excel.Worksheet xlWorksheet;
				// 循环所有DataTable
				for( int i=0; i<ds.Tables.Count; i++ )
				{
					// 添加入一个新的Sheet页
					xlWorksheet = (Excel.Worksheet)xlWorkbook.Worksheets.Add(oMissing,oMissing,1,oMissing);
					xlWorksheet.Name = ds.Tables[i].TableName;
					for (int j = 0; j < ds.Tables[i].Columns.Count; j++) 				//写列标题
					{
						xlWorksheet.Cells[1, j + 1] = ds.Tables[i].Columns[j].ColumnName;
					}
					for (int r = 0; r < ds.Tables[i].Rows.Count; r++) 				//写值
					{
						for (int m = 0; m < ds.Tables[i].Columns.Count; m++)
						{
							xlWorksheet.Cells[r + 2, m + 1] = ds.Tables[i].Rows[r][m];
						}
					}
				}
				xlApp.Visible=true;				
				
			}
			catch  
			{
			
				
			}
		}
    
*****************************************************************************
欢迎使用CSDN论坛专用阅读器 : CSDN Reader(附全部源代码)  
http://www.cnblogs.com/feiyun0112/archive/2006/09/20/509783.html