/*---------------------------------------------------------------- // Copyright (C) 2009 // 版权所有。 // // 文件名: 打开 Excel 文件,写入 DataTable 和图片数据 // 功能描述: 将 DataTable 数据和表头完整导入Excel,其位置可以随意定。如:B4,A1... // 将图片导入到Excel中,并指定导入Excel的位置。如:B5,C6... // 按钮为Button,且可以像HyperLink一样,弹出对话框,让用户将其导出(打开、保存、取消) // // // 修改标识: // 修改描述: // //----------------------------------------------------------------*/ using System; using System.Web; using System.IO; using System.Data; using System.Diagnostics; using System.Runtime.InteropServices; using Excel = Microsoft.Office.Interop.Excel; using Telerik.Web.UI; using System.Data.OleDb; using Provider.Data.Client; /// /// 打开 Excel 文件,写入 DataTable 和图片数据 /// public class DataTableToExcel { private Excel.Application _Excel = null; private Excel.Workbooks _Workbooks = null; private Excel.Workbook _Workbook = null; private Excel.Sheets _Sheets = null; private Excel.Worksheet _Worksheet = null; private Excel.Range _Range = null; private object option = System.Reflection.Missing.Value; private string _FilePath = string.Empty; /// /// 打开 Excel 应用程序 /// /// 文件完整路径 public DataTableToExcel(string filePath) { if (File.Exists(filePath)) { File.Delete(filePath); } _FilePath = filePath; //打开对象 _Excel = new Excel.Application(); _Excel.Visible = false; _Excel.DisplayAlerts = false; _Excel.DefaultSaveFormat = Excel.XlFileFormat.xlWorkbookNormal; decimal version = Convert.ToDecimal(_Excel.Version); if (version < 11.0M) { // MessageBox.Show(" 您的 Excel 版本低于 11.0 (Office 2003),操作可能会出现问题。"); _Excel.Quit(); return; } _Workbooks = _Excel.Workbooks; _Workbook = _Workbooks.Add(true); _Sheets = _Workbook.Worksheets; } /// /// 将图片插入到指定的单元格位置。 /// 注意:图片必须是绝对物理路径 /// /// 单元格名称,例如:B4 /// 要插入图片的绝对路径。 public void InsertPicture(string rangeName, string picturePath) { _Worksheet = (Excel.Worksheet)(_Sheets[1]); _Range = _Worksheet.get_Range(rangeName, option); _Range.Select(); Excel.Pictures pics = (Excel.Pictures)_Worksheet.Pictures(option); pics.Insert(picturePath, option); } /// /// 将图片插入到指定的单元格位置,并设置图片的宽度和高度。 /// 注意:图片必须是绝对物理路径 /// /// 单元格名称,例如:B4 /// 要插入图片的绝对路径。 /// 插入后,图片在Excel中显示的宽度。 /// 插入后,图片在Excel中显示的高度。 public void InsertPicture(string rangeName, string picturePath, int pictuteWidth, int pictureHeight) { _Worksheet = (Excel.Worksheet)(_Sheets[1]); _Range = _Worksheet.get_Range(rangeName, option); _Range.Select(); float picLeft = Convert.ToSingle(_Range.Left); float picTop = Convert.ToSingle(_Range.Top); float picWidth = Convert.ToSingle(pictuteWidth); float picHeight = Convert.ToSingle(pictureHeight); // 图片路径 // 是否链接到文件 // 图片插入时是否随文档一起保存 // 图片在文档中的坐标位置(单位:像素) // 图片显示的宽度和高度(单位:像素) _Worksheet.Shapes.AddPicture(picturePath, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, picLeft, picTop, picWidth, picHeight); } /// /// 把数据写入 Excel 第一个工作表 /// /// 插入的表 /// 插入的位置.比如:A1 public void DataTableToExcelSheet(DataTable dt, string rangeName) { _Worksheet = (Excel.Worksheet)(_Sheets[1]); _Range = _Worksheet.get_Range(rangeName, option); _Range.Select(); int rowIndex = _Range.Row; int colIndex = 1; foreach (DataColumn col in dt.Columns) { _Excel.Cells[rowIndex, colIndex] = col.ColumnName; colIndex++; } foreach (DataRow row in dt.Rows) { rowIndex++; for (int i = 1; i <= dt.Columns.Count; i++) { _Excel.Cells[rowIndex, i] = row[i - 1]; } } } /// /// 把数据自动拆分写入 Excel 多个工作表 /// /// 数据表 /// 工作表名称 /// 网格 public void DataTableToExcelSheets(DataTable dt, string sheetName, RadGrid grid) { // 设置单个 Sheet 的最大行数:60000 + 表头 int sheetRows = 1001; // 计算 Sheet 数量 int sheetCount = (dt.Rows.Count - 1) / sheetRows + 1; // 系统的垃圾回收 GC.Collect(); // 工作表的开始行 int startRow; // 工作表的结束行 int endRow; int rowIndex = 0; int colIndex = 0; //对全部Sheet进行操作 for (int sheetIndex = 0; sheetIndex < sheetCount; sheetIndex++) { // 初始化Sheet中的变量 rowIndex = 1; colIndex = 1; // 计算起始行 startRow = sheetIndex * sheetRows; endRow = startRow + sheetRows - 2; if (endRow > dt.Rows.Count - 1) { endRow = dt.Rows.Count - 1; } // 创建一个Sheet if (null == _Worksheet) { _Worksheet = (Excel.Worksheet)_Sheets.Add(Type.Missing, Type.Missing, 1, Type.Missing); } else { _Worksheet = (Excel.Worksheet)_Sheets.Add(Type.Missing, _Worksheet, 1, Type.Missing); } // 设置Sheet的名称 _Worksheet.Name = sheetName + sheetIndex; // 取得标题 foreach (DataColumn col in dt.Columns) { // 获取标题列 Excel.Range range = _Worksheet.get_Range(_Worksheet.Cells[rowIndex, colIndex], _Worksheet.Cells[rowIndex, colIndex]); // 设置标题居中对齐 range.HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter; // 设置标题为粗体 range.Font.Bold = true; // 填充列名,并进行下一列 GridColumn column = grid.Columns.FindByDataField(col.ColumnName); if (column != null) { _Excel.Cells[rowIndex, colIndex++] = column.HeaderText; } else { _Excel.Cells[rowIndex, colIndex++] = col.ColumnName; } } // 取得表格中数量 int dataIndex; for (dataIndex = startRow; dataIndex <= endRow; dataIndex++) { DataRow row = dt.Rows[dataIndex]; //新起一行,当前单元格移至行首 rowIndex++; colIndex = 1; foreach (DataColumn col in dt.Columns) { _Excel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString(); colIndex++; } } // 工作表添加边框 Excel.Range allRange = _Worksheet.get_Range(_Excel.Cells[1, 1], _Excel.Cells[rowIndex, colIndex - 1]); allRange.Columns.AutoFit(); allRange.Borders.LineStyle = 1; } // 删除多余工作表 for (int i = sheetCount + 1; i <= _Sheets.Count; i++) { ((Excel.Worksheet)_Sheets[i]).Delete(); } } /// /// 把数据自动拆分写入 Excel 多个工作表 /// /// 数据表 /// 工作表名称 /// 网格 public void DataTableToExcelOleDb(DataTable dt, string sheetName, RadGrid grid) { // 组织工作表数据 DataTable dtTable = dt.Copy(); foreach (DataColumn col in dtTable.Columns) { GridColumn column = grid.Columns.FindByDataField(col.ColumnName); if (column != null) { col.ColumnName = "[" + column.HeaderText + "]"; } } // 设置单个 Sheet 的最大行数:60000 + 表头 int sheetRows = 60001; // 计算 Sheet 数量 int sheetCount = (dtTable.Rows.Count - 1) / sheetRows + 1; // 系统的垃圾回收 GC.Collect(); // 工作表的开始行 int startRow; // 工作表的结束行 int endRow; //对全部Sheet进行操作 for (int sheetIndex = 0; sheetIndex < sheetCount; sheetIndex++) { // 计算起始行 startRow = sheetIndex * sheetRows; endRow = startRow + sheetRows - 2; if (endRow > dtTable.Rows.Count - 1) { endRow = dtTable.Rows.Count - 1; } // 创建一个Sheet DataClient client = new DataClient(); string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + _FilePath + ";Extended Properties=Excel 8.0;"; // 设置Sheet的名称 string sheetItem = sheetName + sheetIndex; client.Initialize("Excel", Provider.Base.Service.DataType.Excel, connectionString); string command = string.Empty; // 添加标题行 command = "CREATE TABLE [" + sheetItem + "]("; foreach (DataColumn col in dtTable.Columns) { command += col.ColumnName + " TEXT, "; } command = command.Substring(0, command.Length - 2); command += ")"; client.Execute(command); // 获取工作表结构 string cmd = "SELECT * FROM [" + sheetItem + "]"; OleDbDataAdapter adapter = new OleDbDataAdapter(cmd, connectionString); OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter); // 设置 INSERT 语句中保留字符(起始位置) builder.QuotePrefix = "["; // 设置 INSERT 语句中保留字符(结束位置) builder.QuoteSuffix = "]"; // 填充工作表结构 DataSet dsTemp = new DataSet(); adapter.Fill(dsTemp, "temp"); // 组织工作表数据 DataTable dtSheet = dtTable.Clone(); for (int dataIndex = startRow; dataIndex <= endRow; dataIndex++) { dtSheet.ImportRow(dtTable.Rows[dataIndex]); } CopyDataTable(dtSheet, dsTemp.Tables["temp"]); // 批量更新数据 adapter.Update(dsTemp, "temp"); } //打开对象 _Excel = new Excel.Application(); _Excel.Visible = false; _Excel.DisplayAlerts = false; _Excel.DefaultSaveFormat = Excel.XlFileFormat.xlWorkbookNormal; _Workbooks = _Excel.Workbooks; _Workbook = _Workbooks.Open(_FilePath, option, option, option, option, option, option, option, option, option, option, option, option, option, option); _Sheets = _Workbook.Worksheets; // 删除多余工作表 for (int i = _Sheets.Count; i >= 1; i--) { Excel.Worksheet _Worksheet = (Excel.Worksheet)_Sheets[i]; if (_Worksheet.Name.IndexOf(sheetName) < 0) { _Worksheet.Delete(); } else { Excel.Range range = _Worksheet.get_Range(_Worksheet.Cells[1, 1], _Worksheet.Cells[1, _Worksheet.UsedRange.Columns.Count]); // 设置标题居中对齐 range.HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter; // 设置标题为粗体 range.Font.Bold = true; // 工作表添加边框 range = _Worksheet.get_Range(_Worksheet.Cells[1, 1], _Worksheet.Cells[_Worksheet.UsedRange.Rows.Count, _Worksheet.UsedRange.Columns.Count]); range.Columns.AutoFit(); range.Borders.LineStyle = 1; } } _Workbook.SaveAs(_FilePath, Excel.XlFileFormat.xlWorkbookNormal, option, option, option, option, Excel.XlSaveAsAccessMode.xlNoChange, option, option, option, option, option); } /// /// 两个DataTable的数据对拷 /// /// /// private static void CopyDataTable(DataTable srcTable, DataTable destTable) { foreach (DataRow row in srcTable.Rows) { DataRow drRow = destTable.NewRow(); for (int i = 0; i < destTable.Columns.Count; i++) { drRow[i] = row[i]; } destTable.Rows.Add(drRow); } } /// /// 保存 Excel 文件 /// public void SaveFile() { _Workbook.SaveAs(_FilePath, Excel.XlFileFormat.xlWorkbookNormal, option, option, option, option, Excel.XlSaveAsAccessMode.xlNoChange, option, option, option, option, option); Close(); } /// /// 下載文件 /// public void DownloadFile() { HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ContentType = "application/x-download"; HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=/"" + HttpUtility.UrlEncode(Path.GetFileName(_FilePath).Trim()) + "/""); byte[] file = File.ReadAllBytes(_FilePath); File.Delete(_FilePath); HttpContext.Current.Response.BinaryWrite(file); HttpContext.Current.Response.Flush(); HttpContext.Current.Response.End(); } /// /// 关闭应用程序 /// public void Close() { try { _Workbook.Close(false, option, option); _Workbooks.Close(); _Excel.Quit(); } catch { } IntPtr hwnd = new IntPtr(_Excel.Hwnd); int id = 0; System.Diagnostics.Process[] ps = System.Diagnostics.Process.GetProcessesByName("Excel"); foreach (System.Diagnostics.Process p in ps) { p.Kill(); } } }