using System; using System.Web; using Excel; using System.Drawing; using System.IO; using System.Reflection; using System.Data; using System.Web.UI; using System.Web.UI.WebControls; /// <summary> /// DataSet数据写入Excel保存自定义名称到默认文件夹内(C:\web\SaveFile) /// </summary> /// <param name="ds">System.Data.DataSet数据</param> /// <param name="filename">文件名称(不含后缀)如"Wenjian"</param> public static void WriteExcel(System.Data.DataSet ds, string filename) { System.Data.DataTable dt = ds.Tables[0]; //dt.Columns[0] //Excel.Application excel = new Excel.Application();//引用Excel对象 //excel.Application.Workbooks.Add(true );//引用Excel工作簿 //excel.Cells[ 1 , 1 ] = "First Row First Column"; //excel.Cells[ 1 , 2 ] = "First Row Second Column"; //excel.Cells[ 2 , 1 ] = "Second Row First Column"; //excel.Cells[2, 2] = "Second Row Second Column"; //excel.Visible = true; //使Excel可视 //创建Application对象 Excel.Application xApp = new Excel.ApplicationClass(); xApp.Visible = false; ////得到WorkBook对象, 可以用两种方式之一: 下面的是打开已有的文件 //Excel.Workbook xBook = xApp.Workbooks._Open(@"C:\web\SaveFile\az.xls", //Missing.Value, Missing.Value, Missing.Value, Missing.Value //, Missing.Value, Missing.Value, Missing.Value, Missing.Value //, Missing.Value, Missing.Value, Missing.Value, Missing.Value); Excel.Workbook xBook = xApp.Workbooks.Add(Missing.Value);//新建文件的代码 //指定要操作的Sheet,两种方式: Excel.Worksheet xSheet = (Excel.Worksheet)xBook.Sheets[1]; //Excel.Worksheet xSheet=(Excel.Worksheet)xApp.ActiveSheet; ////读取数据,通过Range对象 //Excel.Range rng1 = xSheet.get_Range("A1", Type.Missing); //rng1.Value2 = "aaa"; ////读取,通过Range对象,但使用不同的接口得到Range ////Excel.Range rng2 = (Excel.Range)xSheet.Cells[1,2]; ////rng2.Value2 = "bbb"; //((Excel.Range)xSheet.Cells[1, 2]).Value="ccc"; ////写入数据 //Excel.Range rng3 = xSheet.get_Range("B2", Missing.Value); //rng3.Value2 = "Hello"; //rng3.Interior.ColorIndex = 6; //设置Range的背景色 for (int i = 0; i < dt.Columns.Count; i++) { ((Excel.Range)xSheet.Cells[1, i + 1]).Value = dt.Columns[i].ColumnName; for (int j = 0; j < dt.Rows.Count; j++) { ((Excel.Range)xSheet.Cells[j + 2, i + 1]).Value = dt.Rows[j][i]; } } string pFilePath = @"C:\web\SaveFile\" + filename ?? System.DateTime.Now.ToString("yyyyMMdd") + ".xlsx"; ////保存方式一:保存WorkBook if (File.Exists(pFilePath)) { File.Delete(pFilePath); } xBook.SaveAs(pFilePath, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); ////保存方式二:保存WorkSheet //xSheet.SaveAs(@"../SaveFile/CData2.xls", //Missing.Value, Missing.Value, Missing.Value, Missing.Value, //Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); //保存方式三 //xBook.Save(); xSheet = null; xBook = null; xApp.Quit(); //这一句是非常重要的,否则Excel对象不能从内存中退出 xApp = null; }
封装到类库ExcelHelper
直接调用