.NET开发不可不知、不可不用的辅助类(三)(报表导出---终结版)

本文介绍使用.NET进行报表导出的方法,包括直接网页输出Excel格式和使用Excel模板两种方式。提供了详细的代码示例,涵盖创建报表辅助类、设置报表属性、导出数据等功能。
.NET导出报表一般是采用导出Excel报表的方式输出内容。而这又分为两种方式:使用Excel模板方式和使用网页输出Excel格式两种。
首先介绍简单的一种,网页输出Excel内容,这种不需要引用Excel的程序集。
ExpandedBlockStart.gifContractedBlock.gif    /**//// <summary>
InBlock.gif    
/// 报表导出辅助类
ExpandedBlockEnd.gif    
/// </summary>

None.gif    public class ExportToExcel
ExpandedBlockStart.gifContractedBlock.gif    
dot.gif{
ContractedSubBlock.gifExpandedSubBlockStart.gif        
字段信息#region 字段信息
InBlock.gif
InBlock.gif        
private const string C_HTTP_HEADER_CONTENT = "Content-Disposition";
InBlock.gif        
private const string C_HTTP_ATTACHMENT = "attachment;filename=";
InBlock.gif        
private const string C_HTTP_CONTENT_TYPE_EXCEL = "application/ms-excel";
InBlock.gif        
private string charSet = "utf-8";
InBlock.gif        
private string fileName = "Report";
InBlock.gif        
private string title = "";
InBlock.gif        
private DataTable sourceTable;
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 输出的字符集,默认为gb2312
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        public string CharSet
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif            
get dot.gifreturn charSet; }
ExpandedSubBlockStart.gifContractedSubBlock.gif            
set dot.gif{ charSet = value; }
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 输出的Excel报表文件名称
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        public string FileName
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif            
get dot.gifreturn fileName; }
ExpandedSubBlockStart.gifContractedSubBlock.gif            
set dot.gif{ fileName = value; }
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 报表内容的抬头
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        public string Title
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif            
get dot.gifreturn title; }
ExpandedSubBlockStart.gifContractedSubBlock.gif            
set dot.gif{ title = value; }
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 报表数据的DataTable
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        public DataTable SourceTable
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif            
get dot.gifreturn sourceTable; }
ExpandedSubBlockStart.gifContractedSubBlock.gif            
set dot.gif{ sourceTable = value; }
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockEnd.gif        
#endregion
        
InBlock.gif
InBlock.gif        
public ExportToExcel()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 带参数的构造函数
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="fileName">导出的Excel文件名</param>
InBlock.gif        
/// <param name="sourceTable">源数据DataTable</param>
ExpandedSubBlockEnd.gif        
/// <param name="title">报表的抬头</param>

InBlock.gif        public ExportToExcel(string fileName, DataTable sourceTable, string title)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
this.fileName = fileName;
InBlock.gif            
this.sourceTable = sourceTable;
InBlock.gif            
this.title = title;
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
public void ExportReport()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if (SourceTable == null || SourceTable.Rows.Count == 0)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return;
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            DataGrid dataGrid 
= new DataGrid();
InBlock.gif            dataGrid.DataSource 
= sourceTable;
InBlock.gif            dataGrid.DataBind();
InBlock.gif
InBlock.gif            HttpResponse Response 
= HttpContext.Current.Response;
InBlock.gif            Response.Clear();
InBlock.gif            Response.Buffer 
= true;
InBlock.gif            Response.AddHeader(C_HTTP_HEADER_CONTENT, C_HTTP_ATTACHMENT 
+ HttpUtility.UrlEncode(fileName + ".xls"));
InBlock.gif            Response.ContentType 
= C_HTTP_CONTENT_TYPE_EXCEL;
InBlock.gif            Response.ContentEncoding 
= Encoding.GetEncoding("gb2312");
InBlock.gif            Response.Charset 
= charSet;
InBlock.gif
InBlock.gif            StringWriter oStringWriter 
= new StringWriter();
InBlock.gif            HtmlTextWriter oHtmlTextWriter 
= new HtmlTextWriter(oStringWriter);
InBlock.gif            dataGrid.RenderControl(oHtmlTextWriter);
InBlock.gif
InBlock.gif            
string str = oStringWriter.ToString();
InBlock.gif            
int trPosition = str.IndexOf("<tr>"0);
InBlock.gif            
string str1 = str.Substring(0, trPosition - 1);
InBlock.gif            
string str2 = str.Substring(trPosition, str.Length - trPosition);
InBlock.gif
InBlock.gif            
string str3 = "\r\n\t<tr>";
InBlock.gif            str3 
+= "\r\n\t\t<td align=\"center\" colspan=\"" + sourceTable.Rows.Count +
InBlock.gif
                    "\" style=\"font-size:14pt;    font-weight:bolder;height:30px;\">" + title + "</td>";
InBlock.gif
            str3 += "\r\n\t</tr>";
InBlock.gif
InBlock.gif            Response.Write(str1 
+ str3 + str2);
InBlock.gif            Response.End();
ExpandedSubBlockEnd.gif        }

ExpandedBlockEnd.gif    }

使用时候代码如下:
None.gif        private void btnExport2_Click(object sender, EventArgs e)
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif{
InBlock.gif            DataTable table 
= SelectAll().Tables[0];
InBlock.gif            ExportToExcel export 
= new ExportToExcel("TestExport", table, "TestExport");
InBlock.gif            export.ExportReport();
ExpandedBlockEnd.gif        }

None.gif
None.gif        
public static DataSet SelectAll()
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif{
InBlock.gif            
string sqlCommand = " Select ID, Name, Age, Man, CONVERT(CHAR(10), Birthday ,120) as Birthday from Test";
InBlock.gif
InBlock.gif            DataSet ds 
= new DataSet();
InBlock.gif            
string connectionString = "Server=localhost;Database=Test;uid=sa;pwd=123456";
InBlock.gif
InBlock.gif            SqlDataAdapter adapter 
= new SqlDataAdapter(sqlCommand, connectionString);
InBlock.gif            adapter.Fill(ds);
InBlock.gif
InBlock.gif            
return ds;
ExpandedBlockEnd.gif        }


另外一种就是先定义好Excel模板,然后输出指定格式的内容,这些内容通过开始单元格名称定位,然后写入内容,但是这种功能比较强大,输出的Excel内容也比较整齐。
1. 首先在Web.Config中配置下
 <system.web>
   <identity impersonate="true"></identity>   
 </system.web>
2. 创建一个Excel模板文件,如下图所示,当然这个是简单的Excel模板,你可以定义很复杂
 Report_Excel.jpg
3. 在网站的根目录中创建一个Temp目录,给EveryOne读写权限,当然你也可以给AuthenticatedUsers
4. 辅助类代码
ExpandedBlockStart.gifContractedBlock.gif    /**//// <summary>
InBlock.gif    
/// 报表导出基类
ExpandedBlockEnd.gif    
/// </summary>

None.gif    public abstract class BaseReport
ExpandedBlockStart.gifContractedBlock.gif    
dot.gif{
ContractedSubBlock.gifExpandedSubBlockStart.gif        
变量及属性#region 变量及属性
InBlock.gif
InBlock.gif        
protected const string C_HTTP_HEADER_CONTENT = "Content-Disposition";
InBlock.gif        
protected const string C_HTTP_ATTACHMENT = "attachment;filename=";
InBlock.gif        
protected const string C_HTTP_INLINE = "inline;filename=";
InBlock.gif        
protected const string C_HTTP_CONTENT_TYPE_EXCEL = "application/ms-excel";
InBlock.gif        
protected const string C_HTTP_CONTENT_LENGTH = "Content-Length";
InBlock.gif        
protected const string C_ERROR_NO_RESULT = "Data not found.";
InBlock.gif
InBlock.gif        
protected string CharSet = "utf-8";
InBlock.gif        
protected string fileName;
InBlock.gif        
protected string sheetName; //表名称
InBlock.gif
        private ExcelHelper excelHelper;
InBlock.gif
ExpandedSubBlockEnd.gif        
#endregion

InBlock.gif
InBlock.gif        
public BaseReport()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            excelHelper 
= new ExcelHelper(false);
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 打开Excel文件和关闭Excel
InBlock.gif        
/// </summary>        
ExpandedSubBlockEnd.gif        
/// <returns>返回OK表示成功</returns>

InBlock.gif        protected virtual bool OpenFile()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
return excelHelper.OpenFile(fileName);
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 关闭工作薄和excel文件
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        protected virtual void CloseFile()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            excelHelper.stopExcel();
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 导出EXCEL文件
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        protected virtual void ExportFile()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
string tempFileName = HttpContext.Current.Request.PhysicalApplicationPath + @"Temp\" + sheetName.Replace(".xls""");
InBlock.gif            
string SaveFileName = tempFileName + DateTime.Now.ToLongDateString() +
InBlock.gif                                  DateTime.Now.ToLongTimeString().Replace(
":""-"+ ".xls";
InBlock.gif            excelHelper.SaveAsFile(SaveFileName);
InBlock.gif            CloseFile();
InBlock.gif
InBlock.gif            HttpResponse Response 
= HttpContext.Current.Response;
InBlock.gif            Response.Clear();
InBlock.gif            Response.Buffer 
= true;
InBlock.gif            Response.AddHeader(C_HTTP_HEADER_CONTENT,
InBlock.gif                               C_HTTP_ATTACHMENT 
+ HttpUtility.UrlEncode(DateTime.Now.ToLongDateString() + sheetName));
InBlock.gif            Response.ContentType 
= C_HTTP_CONTENT_TYPE_EXCEL;
InBlock.gif            Response.ContentEncoding 
= Encoding.GetEncoding("gb2312");
InBlock.gif            Response.Charset 
= CharSet;
InBlock.gif            Response.WriteFile(SaveFileName);
InBlock.gif            Response.Flush();
InBlock.gif            Response.Clear();
InBlock.gif
InBlock.gif            File.Delete(SaveFileName);
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 填充表单数据到excel中
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="GotoCell">定义的首个Cell名称</param>
ExpandedSubBlockEnd.gif        
/// <param name="dt">数据表Datatable</param>

InBlock.gif        protected virtual void FillCell(string GotoCell, DataTable dt)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
int BeginRow = 2;
InBlock.gif            
int RowCount = dt.Rows.Count;
InBlock.gif            Range rgFill 
= excelHelper.GotoCell(GotoCell);
InBlock.gif            
if (RowCount > BeginRow)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                excelHelper.InsertRows(rgFill.Row 
+ 1, RowCount - BeginRow); //从定位处的下一行的上面插入新行
ExpandedSubBlockEnd.gif
            }

InBlock.gif            
//Fill
InBlock.gif
            if (RowCount > 0)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                excelHelper.DataTableToExcelofObj(dt, excelHelper.IntToLetter(rgFill.Column) 
+ rgFill.Row.ToString(), false);
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
private void AppendTitle(string titleAppendix)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if (titleAppendix != null && titleAppendix != string.Empty)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
try
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    excelHelper.AppendToExcel(titleAppendix, 
"Title");
ExpandedSubBlockEnd.gif                }

InBlock.gif                
catch (Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
throw new Exception("您没有指定一个Title的单元格", ex);
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 写入内容
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        public virtual void ExportExcelFile()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            ExportExcelFile(
string.Empty);
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 写入内容并追加标题内容
InBlock.gif        
/// </summary>
ExpandedSubBlockEnd.gif        
/// <param name="titleAppendix">追加在Title后面的内容(一般如年月份)</param>

InBlock.gif        public virtual void ExportExcelFile(string titleAppendix)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                OpenFile();
InBlock.gif                AppendTitle(titleAppendix);
InBlock.gif                FillFile();
InBlock.gif                ExportFile();
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch //(Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif
            dot.gif{
InBlock.gif                CloseFile();
InBlock.gif                
throw;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif
InBlock.gif        
protected virtual void FillFile()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
ExpandedSubBlockEnd.gif        }

ExpandedBlockEnd.gif    }

ExpandedBlockStart.gifContractedBlock.gif    /**//// <summary>
InBlock.gif    
///通用的报表导出类
InBlock.gif    
/// </summary>
InBlock.gif    
/// <example>
InBlock.gif    
/// <code>
InBlock.gif    
/// DataTable dt = InitTableData(); //InitTableData为自定义获取数据表的函数
InBlock.gif    
///    CommonExport report = new CommonExport(dt, "架空线.xls", "Start"); //Start是Excel一个单元格名称
InBlock.gif    
/// report.ExportExcelFile();
InBlock.gif    
/// </code>
ExpandedBlockEnd.gif    
/// </example>

None.gif    public class CommonExport : BaseReport
ExpandedBlockStart.gifContractedBlock.gif    
dot.gif{
InBlock.gif        
private DataTable sourceTable;
InBlock.gif        
private string startCellName;
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 构造函数
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="sourceTable">要导出的DataTable对象</param>
InBlock.gif        
/// <param name="excelFileName">相对于根目录的文件路径,如Model/Test.xls</param>
ExpandedSubBlockEnd.gif        
/// <param name="startCellName">开始的单元格名称</param>

InBlock.gif        public CommonExport(DataTable sourceTable, string excelFileName, string startCellName)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            fileName 
= Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, excelFileName);
InBlock.gif            sheetName 
= Path.GetFileName(fileName);
InBlock.gif
InBlock.gif            
this.sourceTable = sourceTable;
InBlock.gif            
this.startCellName = startCellName;
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 填写文件
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        protected override void FillFile()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            FillCell(startCellName, sourceTable);
ExpandedSubBlockEnd.gif        }

ExpandedBlockStart.gifContractedBlock.gif    /**//// <summary>
InBlock.gif    
/// Excel帮助类
ExpandedBlockEnd.gif    
/// </summary>

None.gif    internal class ExcelHelper : IDisposable
ExpandedBlockStart.gifContractedBlock.gif    
dot.gif{
ContractedSubBlock.gifExpandedSubBlockStart.gif        
一般的属性变量#region 一般的属性变量
InBlock.gif
InBlock.gif        
private Application excelApp = null;
InBlock.gif        
private Windows excelWindows = null;
InBlock.gif        
private Window excelActiveWindow = null;
InBlock.gif        
private Workbooks excelWorkbooks = null;
InBlock.gif        
private Workbook excelWorkbook = null;
InBlock.gif        
private Sheets excelSheets = null;
InBlock.gif        
private Worksheet excelWorksheet = null;
InBlock.gif
InBlock.gif        
private static object m_missing = Missing.Value;
InBlock.gif        
private static object m_visible = true;
InBlock.gif        
private static object m_false = false;
InBlock.gif        
private static object m_true = true;
InBlock.gif        
private bool m_app_visible = false;
InBlock.gif        
private object m_filename;
InBlock.gif
ExpandedSubBlockEnd.gif        
#endregion

InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif        
打开工作薄变量#region 打开工作薄变量
InBlock.gif
InBlock.gif        
private object _update_links = 0;
InBlock.gif        
private object _read_only = m_false;
InBlock.gif        
private object _format = 1;
InBlock.gif        
private object _password = m_missing;
InBlock.gif        
private object _write_res_password = m_missing;
InBlock.gif        
private object _ignore_read_only_recommend = m_true;
InBlock.gif        
private object _origin = m_missing;
InBlock.gif        
private object _delimiter = m_missing;
InBlock.gif        
private object _editable = m_false;
InBlock.gif        
private object _notify = m_false;
InBlock.gif        
private object _converter = m_missing;
InBlock.gif        
private object _add_to_mru = m_false;
InBlock.gif        
private object _local = m_false;
InBlock.gif        
private object _corrupt_load = m_false;
InBlock.gif
ExpandedSubBlockEnd.gif        
#endregion

InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif        
关闭工作薄变量#region 关闭工作薄变量
InBlock.gif
InBlock.gif        
private object _save_changes = m_false;
InBlock.gif        
private object _route_workbook = m_false;
InBlock.gif
ExpandedSubBlockEnd.gif        
#endregion

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 当前工作薄
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        public Workbook CurrentExcelWorkBook
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif            
get dot.gifreturn excelWorkbook; }
ExpandedSubBlockStart.gifContractedSubBlock.gif            
set dot.gif{ excelWorkbook = value; }
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 释放对象内存,推出进程
InBlock.gif        
/// </summary>
ExpandedSubBlockEnd.gif        
/// <param name="obj"></param>

InBlock.gif        private void NAR(object obj)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                Marshal.ReleaseComObject(obj);
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
ExpandedSubBlockEnd.gif            }

InBlock.gif            
finally
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                obj 
= null;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif
InBlock.gif        
public ExcelHelper()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            StartExcel();
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 确定Excel打开是否可见
InBlock.gif        
/// </summary>
ExpandedSubBlockEnd.gif        
/// <param name="visible">true为可见</param>

InBlock.gif        public ExcelHelper(bool visible)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            m_app_visible 
= visible;
InBlock.gif            StartExcel();
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 开始Excel应用程序
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        private void StartExcel()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if (excelApp == null)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                excelApp 
= new ApplicationClass();
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
// Excel是否可见
InBlock.gif
            excelApp.Visible = m_app_visible;
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
public void Dispose()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            stopExcel();
InBlock.gif            GC.SuppressFinalize(
this);
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
ContractedSubBlock.gifExpandedSubBlockStart.gif        
打开、保存、关闭Excel文件#region 打开、保存、关闭Excel文件
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 打开Excel文件和关闭Excel
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="fileName">文件名</param>
ExpandedSubBlockEnd.gif        
/// <returns>返回OK表示成功</returns>

InBlock.gif        public bool OpenFile(string fileName)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
return OpenFile(fileName, string.Empty);
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 打开Excel文件
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="fileName">文件名</param>
InBlock.gif        
/// <param name="password">密码</param>
ExpandedSubBlockEnd.gif        
/// <returns>返回OK表示成功</returns>

InBlock.gif        public bool OpenFile(string fileName, string password)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            m_filename 
= fileName;
InBlock.gif
InBlock.gif            
if (password.Length > 0)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                _password 
= password;
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
// 打开工作薄 
InBlock.gif
                excelWorkbook = excelApp.Workbooks.Open(
InBlock.gif                    fileName,
InBlock.gif                    _update_links, _read_only, _format, _password, _write_res_password,
InBlock.gif                    _ignore_read_only_recommend, _origin, _delimiter, _editable, _notify,
InBlock.gif                    _converter, _add_to_mru, _local, _corrupt_load);
InBlock.gif
InBlock.gif                excelSheets 
= excelWorkbook.Worksheets;
InBlock.gif                excelWorksheet 
= (Worksheet) excelSheets.get_Item(1);
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                CloseFile();
InBlock.gif                
return false;
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
return true;
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 关闭工作薄
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        public void CloseFile()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
foreach (Workbook workbook in excelWorkbooks)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                workbook.Close(_save_changes, m_filename, _route_workbook);
InBlock.gif                NAR(workbook);
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif
InBlock.gif        
public void SaveFile(string workbook)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            FindExcelWorkbook(workbook);
InBlock.gif            excelWorkbook.Save();
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 保存文件
InBlock.gif        
/// </summary>
ExpandedSubBlockEnd.gif        
/// <param name="outputFile">输出的文件名</param>

InBlock.gif        public void SaveAsFile(string outputFile)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            SaveAsFile(
string.Empty, outputFile);
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 保存指定工作薄的文件
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="workbook">工作薄</param>
ExpandedSubBlockEnd.gif        
/// <param name="outputFile">输出的文件名</param>

InBlock.gif        public void SaveAsFile(string workbook, string outputFile)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if (File.Exists(outputFile))
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
try
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    File.Delete(outputFile);
ExpandedSubBlockEnd.gif                }

InBlock.gif                
catch
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
return;
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
if (workbook != string.Empty)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                FindExcelWorkbook(workbook);
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            excelWorkbook.SaveAs(outputFile,
InBlock.gif                                 Type.Missing, _password, _write_res_password, Type.Missing, Type.Missing,
InBlock.gif                                 XlSaveAsAccessMode.xlExclusive,
InBlock.gif                                 Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 杀掉Excel进程.退出Excel应用程序.
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        public void stopExcel()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            excelApp.Quit();
InBlock.gif            NAR(excelSheets);
InBlock.gif            NAR(excelWorksheet);
InBlock.gif            NAR(excelWorkbooks);
InBlock.gif            NAR(excelWorkbook);
InBlock.gif            NAR(excelWindows);
InBlock.gif            NAR(excelActiveWindow);
InBlock.gif            NAR(excelApp);
InBlock.gif
InBlock.gif            GC.Collect();
InBlock.gif            
if (excelApp != null)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                Process[] pProcess;
InBlock.gif                pProcess 
= Process.GetProcessesByName("EXCEL");
InBlock.gif                pProcess[
0].Kill();
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockEnd.gif        
#endregion
        
InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif        
windows窗口,workbook工作薄,worksheet工作区操作#region windows窗口,workbook工作薄,worksheet工作区操作
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 得到工作薄的工作区集合
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        public void GetExcelSheets()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if (excelWorkbook != null)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                excelSheets 
= excelWorkbook.Worksheets;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 找到活动的excel window
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="workWindowName">窗口名称</param>
ExpandedSubBlockEnd.gif        
/// <returns></returns>

InBlock.gif        public bool FindExcelWindow(string workWindowName)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
bool WINDOW_FOUND = false;
InBlock.gif
InBlock.gif            excelWindows 
= excelApp.Windows;
InBlock.gif            
if (excelWindows != null)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
for (int i = 1; i < excelWindows.Count; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    excelActiveWindow 
= excelWindows.get_Item(i);
InBlock.gif                    
if (excelActiveWindow.Caption.ToString().Equals(workWindowName))
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        excelActiveWindow.Activate();
InBlock.gif                        WINDOW_FOUND 
= true;
InBlock.gif                        
break;
ExpandedSubBlockEnd.gif                    }

ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif            
InBlock.gif            
return WINDOW_FOUND;
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 查找工作薄
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="workbookName">工作薄名</param>
ExpandedSubBlockEnd.gif        
/// <returns>true为发现</returns>

InBlock.gif        public bool FindExcelWorkbook(string workbookName)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
bool WORKBOOK_FOUND = false;
InBlock.gif            excelWorkbooks 
= excelApp.Workbooks;
InBlock.gif            
if (excelWorkbooks != null)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
for (int i = 1; i < excelWorkbooks.Count; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    excelWorkbook 
= excelWorkbooks.get_Item(i);
InBlock.gif                    
if (excelWorkbook.Name.Equals(workbookName))
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        excelWorkbook.Activate();
InBlock.gif                        WORKBOOK_FOUND 
= true;
InBlock.gif                        
break;
ExpandedSubBlockEnd.gif                    }

ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif            
return WORKBOOK_FOUND;
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 查找工作区
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="worksheetName"></param>
ExpandedSubBlockEnd.gif        
/// <returns>true为发现</returns>

InBlock.gif        public bool FindExcelWorksheet(string worksheetName)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
bool SHEET_FOUND = false;
InBlock.gif
InBlock.gif            excelSheets 
= excelWorkbook.Worksheets;
InBlock.gif
InBlock.gif            
if (excelSheets != null)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
for (int i = 1; i <= excelSheets.Count; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    excelWorksheet 
= (Worksheet) excelSheets.get_Item((object) i);
InBlock.gif                    
if (excelWorksheet.Name.Equals(worksheetName))
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        excelWorksheet.Activate();
InBlock.gif                        SHEET_FOUND 
= true;
InBlock.gif                        
break;
ExpandedSubBlockEnd.gif                    }

ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif            
return SHEET_FOUND;
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockEnd.gif        
#endregion

InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif        
行列操作#region 行列操作
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 得到工作区的选择范围的数组
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        public string[] GetRange(string startCell, string endCell)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            Range workingRangeCells 
= excelWorksheet.get_Range(startCell, endCell);
InBlock.gif            workingRangeCells.Select();
InBlock.gif            Array array 
= (Array) workingRangeCells.Cells.Value2;
InBlock.gif            
string[] arrayS = ConvertToStringArray(array);
InBlock.gif
InBlock.gif            
return arrayS;
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 将二维数组数据写入Excel文件(不分页)
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        public void ArrayToExcel(string[,] arr, string getCell)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
int rowCount = arr.GetLength(0); //二维数组行数(一维长度)
InBlock.gif
            int colCount = arr.GetLength(1); //二维数据列数(二维长度)
InBlock.gif

InBlock.gif            Range range 
= excelWorksheet.get_Range(getCell, Type.Missing);
InBlock.gif            range 
= range.get_Resize(rowCount, colCount);
InBlock.gif            range.HorizontalAlignment 
= XlHAlign.xlHAlignCenter;
InBlock.gif            range.VerticalAlignment 
= XlVAlign.xlVAlignCenter;
InBlock.gif
InBlock.gif            range.set_Value(Missing.Value, arr);
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
public void ArrayToExcel(object[,] arr, string getCell)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
int rowCount = arr.GetLength(0); //二维数组行数(一维长度)
InBlock.gif
            int colCount = arr.GetLength(1); //二维数据列数(二维长度)
InBlock.gif

InBlock.gif            Range range 
= excelWorksheet.get_Range(getCell, Type.Missing);
InBlock.gif            range 
= range.get_Resize(rowCount, colCount);
InBlock.gif            range.HorizontalAlignment 
= XlHAlign.xlHAlignCenter;
InBlock.gif            range.VerticalAlignment 
= XlVAlign.xlVAlignCenter;
InBlock.gif            range.Value2 
= arr;
InBlock.gif
InBlock.gif            
//range.set_Value(System.Reflection.Missing.Value,arr);
ExpandedSubBlockEnd.gif
        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 合并单元格
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="startCell">开始Cell</param>
InBlock.gif        
/// <param name="endCell">结束Cell</param>
ExpandedSubBlockEnd.gif        
/// <param name="text">填写文字</param>

InBlock.gif        public void MergeCell(string startCell, string endCell, string text)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            MergeCell(
string.Empty, startCell, endCell, text);
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 合并单元格
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="workbookName"></param>
InBlock.gif        
/// <param name="startCell"></param>
InBlock.gif        
/// <param name="endCell"></param>
ExpandedSubBlockEnd.gif        
/// <param name="text"></param>

InBlock.gif        public void MergeCell(string workbookName, string startCell, string endCell, string text)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if (workbookName != string.Empty)
InBlock.gif                FindExcelWorkbook(workbookName);
InBlock.gif
InBlock.gif            Range range 
= excelWorksheet.get_Range(startCell, endCell);
InBlock.gif            range.ClearContents();
InBlock.gif            range.MergeCells 
= true;
InBlock.gif            range.Value2 
= text;
InBlock.gif            range.HorizontalAlignment 
= XlHAlign.xlHAlignCenter;
InBlock.gif            range.VerticalAlignment 
= XlVAlign.xlVAlignCenter;
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 添加样式
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="styleName">样式名</param>
InBlock.gif        
/// <param name="fontName">字体名</param>
InBlock.gif        
/// <param name="fontSize">字体大小</param>
InBlock.gif        
/// <param name="fontColor">字体Color(0-255)</param>
ExpandedSubBlockEnd.gif        
/// <param name="interiorColor">Range的填充Color(0-255)</param>

InBlock.gif        public void AddStyle(string styleName, string fontName, int fontSize, int fontColor, int interiorColor)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                Style existStyle 
= excelWorkbook.Styles[styleName];
InBlock.gif                
return;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            Style style 
= excelWorkbook.Styles.Add(styleName, Type.Missing);
InBlock.gif            style.Font.Name 
= fontName;
InBlock.gif            style.Font.Size 
= fontSize;
InBlock.gif            
InBlock.gif            
if (fontColor >= 0 && fontColor <= 255)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                style.Font.Color 
= fontColor;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
if (fontColor >= 0 && fontColor <= 255)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                style.Interior.Color 
= fontColor;
ExpandedSubBlockEnd.gif            }

InBlock.gif            style.Interior.Pattern 
= XlPattern.xlPatternSolid;
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 应用样式
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="startCell">Range的开始</param>
InBlock.gif        
/// <param name="endCell">Range的结束</param>
ExpandedSubBlockEnd.gif        
/// <param name="styleName">样式名</param>

InBlock.gif        public void ApplyStyle(string startCell, string endCell, string styleName)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            Style style;
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                style 
= excelWorkbook.Styles[styleName];
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
InBlock.gif            Range workingRangeCells 
= excelWorksheet.get_Range(startCell, endCell);
InBlock.gif            workingRangeCells.Style 
= style;
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 插行(在指定行上面插入指定数量行)
InBlock.gif        
/// </summary>
ExpandedSubBlockEnd.gif        
/// <param name="rowIndex">行开始Index</param>

InBlock.gif        public void InsertRows(int rowIndex)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                Range range 
= (Range) excelWorksheet.Rows[rowIndex, Type.Missing];
InBlock.gif                range.Insert(XlDirection.xlDown, Type.Missing);
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 插行(在指定行上面插入指定数量行)
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="rowIndex">行开始Index</param>
ExpandedSubBlockEnd.gif        
/// <param name="count">插入的行数 </param>    

InBlock.gif        public void InsertRows(int rowIndex, int count)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
for (int i = 0; i < count; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    Range range 
= (Range) excelWorksheet.Rows[rowIndex, Type.Missing];
InBlock.gif                    range.Insert(XlDirection.xlDown, Type.Missing);
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 插列(在指定列右边插入指定数量列)
InBlock.gif        
/// </summary>
ExpandedSubBlockEnd.gif        
/// <param name="columnIndex">列开始Index</param>

InBlock.gif        public void InsertColumns(int columnIndex)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                Range range 
= (Range) excelWorksheet.Columns[IntToLetter(columnIndex), Type.Missing];
InBlock.gif                range.Insert(XlDirection.xlToLeft, Type.Missing);
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 指定Cell格填充
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="text">填充内容</param>
ExpandedSubBlockEnd.gif        
/// <param name="getCell">Cell位置</param>

InBlock.gif        public void InsertToExcel(string text, string getCell)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            Range range 
= excelWorksheet.get_Range(getCell, Type.Missing);
InBlock.gif            range.Value2 
= text;
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
public void InsertToExcel(object text, string getCell)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            Range range 
= excelWorksheet.get_Range(getCell, Type.Missing);
InBlock.gif            range.Value2 
= text;
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 往指定Cell格后面追加填充
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="text">追加填充的内容</param>
ExpandedSubBlockEnd.gif        
/// <param name="getCell">Cell位置</param>

InBlock.gif        public void AppendToExcel(string text, string getCell)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            Range range 
= excelWorksheet.get_Range(getCell, Type.Missing);
InBlock.gif            range.Value2 
= range.Value2 + text;
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 删除行
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="rowIndex">行Index</param>
ExpandedSubBlockEnd.gif        
/// <param name="count">行数</param>

InBlock.gif        public void DeleteRows(int rowIndex, int count)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                Range range 
= (Range) excelWorksheet.Rows[rowIndex + ":" + (rowIndex + count - 1), Type.Missing];
InBlock.gif                range.Delete(XlDirection.xlUp);
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 删除列
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="columnIndex">列Index</param>
ExpandedSubBlockEnd.gif        
/// <param name="count">列数</param>

InBlock.gif        public void DeleteColumns(int columnIndex, int count)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
string cells = IntToLetter(columnIndex) + ":" + IntToLetter(columnIndex + count - 1);
InBlock.gif                Range range 
= (Range) excelWorksheet.Columns[cells, Type.Missing];
InBlock.gif                range.Delete(XlDirection.xlDown);
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 将Excel列的整数索引值转换为字符索引值
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="n"></param>
ExpandedSubBlockEnd.gif        
/// <returns></returns>

InBlock.gif        public string IntToLetter(int n)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if (n > 256)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
throw new Exception("索引超出范围,Excel的列索引不能超过256!");
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
int i = Convert.ToInt32(n / 26);
InBlock.gif            
int j = n % 26;
InBlock.gif
InBlock.gif            
char c1 = Convert.ToChar(i + 64);
InBlock.gif            
char c2 = Convert.ToChar(j + 64);
InBlock.gif
InBlock.gif            
if (n > 26)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return c1.ToString() + c2.ToString();
ExpandedSubBlockEnd.gif            }

InBlock.gif            
else if (n == 26)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return "Z";
ExpandedSubBlockEnd.gif            }

InBlock.gif            
else
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return c2.ToString();
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 将Excel列的字母索引值转换成整数索引值
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="letter"></param>
ExpandedSubBlockEnd.gif        
/// <returns></returns>

InBlock.gif        public int LetterToInt(string letter)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if (letter.Trim().Length == 0)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
throw new Exception("不接受空字符串!");
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
int n = 0;
InBlock.gif            
if (letter.Length >= 2)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
char c1 = letter.ToCharArray(02)[0];
InBlock.gif                
char c2 = letter.ToCharArray(02)[1];
InBlock.gif
InBlock.gif                
if (!char.IsLetter(c1) || !char.IsLetter(c2))
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
throw new Exception("格式不正确,必须是字母!");
ExpandedSubBlockEnd.gif                }

InBlock.gif
InBlock.gif                c1 
= char.ToUpper(c1);
InBlock.gif                c2 
= char.ToUpper(c2);
InBlock.gif
InBlock.gif                
int i = Convert.ToInt32(c1) - 64;
InBlock.gif                
int j = Convert.ToInt32(c2) - 64;
InBlock.gif
InBlock.gif                n 
= i*26 + j;
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
if (letter.Length == 1)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
char c1 = letter.ToCharArray()[0];
InBlock.gif
InBlock.gif                
if (!char.IsLetter(c1))
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
throw new Exception("格式不正确,必须是字母!");
ExpandedSubBlockEnd.gif                }

InBlock.gif
InBlock.gif                c1 
= char.ToUpper(c1);
InBlock.gif                n 
= Convert.ToInt32(c1) - 64;
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
if (n > 256)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
throw new Exception("索引超出范围,Excel的列索引不能超过256!");
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
return n;
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// DataTable填充Excel
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="dt">DataTable表</param>
InBlock.gif        
/// <param name="getCell">Cell位置</param>
ExpandedSubBlockEnd.gif        
/// <param name="showHeader">是否显示表头</param>

InBlock.gif        public void DataTableToExcel(DataTable dt, string getCell, bool showHeader)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
int rowCount = dt.Rows.Count; //DataTable行数
InBlock.gif
            int colCount = dt.Columns.Count; //DataTable列数
InBlock.gif

InBlock.gif            
string[,] array;
InBlock.gif            
if (showHeader)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                array 
= new string[rowCount + 1,colCount];
ExpandedSubBlockEnd.gif            }

InBlock.gif            
else
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                array 
= new string[rowCount,colCount];
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
if (showHeader) //添加行字段
ExpandedSubBlockStart.gifContractedSubBlock.gif
            dot.gif{
InBlock.gif                
for (int i = 0; i < colCount; i ++)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    array[
0, i] = dt.Columns[i].ColumnName;
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
for (int j = 0; j < rowCount; j++)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
for (int k = 0; k < colCount; k++)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    array[j 
+ (showHeader ? 1 : 0), k] = dt.Rows[j][k].ToString();
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif            
InBlock.gif            ArrayToExcel(array, getCell);
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// DataTable填充Excel  以object方式填充
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="dt">DataTable表</param>
InBlock.gif        
/// <param name="getCell">Cell位置</param>
ExpandedSubBlockEnd.gif        
/// <param name="showHeader">是否显示表头</param>

InBlock.gif        public void DataTableToExcelofObj(DataTable dt, string getCell, bool showHeader)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
int rowCount = dt.Rows.Count; //DataTable行数
InBlock.gif
            int colCount = dt.Columns.Count; //DataTable列数
InBlock.gif

InBlock.gif            
object[,] array;
InBlock.gif            
if (showHeader)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                array 
= new object[rowCount + 1, colCount];
ExpandedSubBlockEnd.gif            }

InBlock.gif            
else
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                array 
= new object[rowCount, colCount];
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
if (showHeader) //添加行字段
ExpandedSubBlockStart.gifContractedSubBlock.gif
            dot.gif{
InBlock.gif                
for (int i = 0; i < colCount; i ++)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    array[
0, i] = dt.Columns[i].ColumnName;
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
for (int j = 0; j < rowCount; j++)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
for (int k = 0; k < colCount; k++)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    array[j 
+ (showHeader ? 1 : 0), k] = dt.Rows[j][k];
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif            
InBlock.gif            ArrayToExcel(array, getCell);
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// DataRow填充Excel 以object方式填充
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="dr">DataRow</param>
InBlock.gif        
/// <param name="getCell">Cell位置</param>
ExpandedSubBlockEnd.gif        
/// <param name="showHeader">是否显示表头</param>

InBlock.gif        public void DataRowToExcel(DataRow[] dr, string getCell, bool showHeader)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
int rowCount = dr.GetLength(0); //DataRow行数
InBlock.gif
            int colCount = dr[0].Table.Columns.Count; //DataRow列数
InBlock.gif

InBlock.gif            
object[,] array;
InBlock.gif            
if (showHeader)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                array 
= new object[rowCount + 1,colCount];
ExpandedSubBlockEnd.gif            }

InBlock.gif            
else
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                array 
= new object[rowCount,colCount];
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
if (showHeader) //添加行字段
ExpandedSubBlockStart.gifContractedSubBlock.gif
            dot.gif{
InBlock.gif                
for (int i = 0; i < colCount; i ++)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    array[
0, i] = dr[0].Table.Columns[i].ColumnName;
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
for (int j = 0; j < rowCount; j++)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
for (int k = 0; k < colCount; k++)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    array[j 
+ (showHeader ? 1 : 0), k] = dr[j][k];
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif            
InBlock.gif            ArrayToExcel(array, getCell);
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
private Range SelectRange(string range)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
return excelWorksheet.get_Range(range, Type.Missing);
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
public void RangeCopy(string startCell, string endCell, string targetCell)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            RangeCopy(
string.Empty, string.Empty, startCell, endCell, string.Empty, string.Empty, targetCell);
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
public void RangeCopy(string worksheetName, string startCell, string endCell, string targetCell)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            RangeCopy(
string.Empty, worksheetName, startCell, endCell, string.Empty, string.Empty, targetCell);
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
public void RangeCopy(string worksheetName, string startCell, string endCell, string targetWorksheetName,
InBlock.gif                              
string targetCell)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            RangeCopy(
string.Empty, worksheetName, startCell, endCell, string.Empty, targetWorksheetName, targetCell);
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
public void RangeCopy(string workbookName, string worksheetName, string startCell, string endCell,
InBlock.gif                              
string targetWorksheetName, string targetCell)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            RangeCopy(workbookName, worksheetName, startCell, endCell, 
string.Empty, targetWorksheetName, targetCell);
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 区域复制粘贴
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="workbookName">工作薄名</param>
InBlock.gif        
/// <param name="worksheetName">工作区名</param>
InBlock.gif        
/// <param name="startCell">开始Cell</param>
InBlock.gif        
/// <param name="endCell">结束Cell</param>
InBlock.gif        
/// <param name="targetWorkbookName">目标工作薄名</param>
InBlock.gif        
/// <param name="targetWorksheetName">目标工作区名</param>
ExpandedSubBlockEnd.gif        
/// <param name="targetCell">目标Cell</param>

InBlock.gif        public void RangeCopy(string workbookName, string worksheetName, string startCell, string endCell,
InBlock.gif                              
string targetWorkbookName, string targetWorksheetName, string targetCell)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if (workbookName != string.Empty && !FindExcelWorkbook(workbookName))
InBlock.gif                
return;
InBlock.gif
InBlock.gif            
if (worksheetName != string.Empty && !FindExcelWorksheet(worksheetName))
InBlock.gif                
return;
InBlock.gif
InBlock.gif            Range workingRangeCells 
= excelWorksheet.get_Range(startCell, endCell);
InBlock.gif            
if (workingRangeCells == null)
InBlock.gif                
return;
InBlock.gif
InBlock.gif            
if (targetWorkbookName != string.Empty && !FindExcelWorkbook(targetWorkbookName))
InBlock.gif                
return;
InBlock.gif            
if (targetWorksheetName != string.Empty && !FindExcelWorksheet(targetWorksheetName))
InBlock.gif                
return;
InBlock.gif
InBlock.gif            Range targetRange 
= excelWorksheet.get_Range(targetCell, Type.Missing);
InBlock.gif            workingRangeCells.Copy(targetRange);
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 转换Array为字符串数组
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="values">Array</param>
ExpandedSubBlockEnd.gif        
/// <returns>String[]</returns>

InBlock.gif        private string[] ConvertToStringArray(Array values)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
string[] newArray = new string[values.Length];
InBlock.gif
InBlock.gif            
int index = 0;
InBlock.gif            
for (int i = values.GetLowerBound(0); i <= values.GetUpperBound(0); i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
for (int j = values.GetLowerBound(1); j <= values.GetUpperBound(1); j++)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
if (values.GetValue(i, j) == null)
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        newArray[index] 
= "";
ExpandedSubBlockEnd.gif                    }

InBlock.gif                    
else
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        newArray[index] 
= values.GetValue(i, j).ToString();
ExpandedSubBlockEnd.gif                    }

InBlock.gif                    index
++;
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif            
return newArray;
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
public Range GotoCell(string Key)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            excelApp.Goto(Key, 
0);
InBlock.gif            
return excelApp.ActiveCell;
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockEnd.gif        
#endregion
        
ExpandedBlockEnd.gif    }

None.gif

终于写完了,收工
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值