[code=csharp]
//1.添加引用-〉com-〉microsoft excel 11.0 支持Excel2000需创建一个Excel2000的dll
Create an Interop Assembly from the Excel9 Type Library
- Choose a unique name that will distinguish YOUR Interop DLL from others that may be found
- Use the .NET SDK Tool called TLBIMP.exe to build your Interop Assembly from the command line
@echo off
SET prog="C:\Program Files\Microsoft Visual Studio .NET 2003\SDK\v1.1\Bin\TlbImp.exe"
%prog% EXCEL9.OLB /out=My.Excel9.Interop.dll
pause
//2.若出现错误:命名空间“Microsoft.Office”中不存在类型或命名空间名称“Interop”(是缺少程序集引用吗?)
//解决方法:先删除引用中的Excel,然后找到文件Microsoft.Office.Interop.Excel.dll,手动添加该文件的引用
using System;
using System.Data;
using System.Reflection;
using System.IO;
using System.Data.OleDb;
using System.Configuration;
using System.Runtime.InteropServices;
using System.Text;
//using Excel = Microsoft.Office.Interop.Excel; Support for Excel 2003 or later
using Excel = My.Excel9.Interop; //support for Excel 2000
using System.Collections.Generic;
namespace Common
{
/// <summary>
/// 功能描述:对Excel报表进行操作
/// 说明:在工程中需要添加 Excel11.0对象库的引用(Office 2000为Excel9.0,Office XP为Excel10.0);
/// 需要在Dcom中配置Excel应用程序的权限;
/// 服务器需要安装Office2003
/// </summary>
public class ExcelLib
{
#region Variables
private Excel.Application excelApplication = null;
private Excel.Workbooks excelWorkBooks = null;
private Excel.Workbook excelWorkBook = null;
private Excel.Sheets excelWorkSheets = null;
private Excel.Worksheet excelWorkSheet = null;
private Excel.Range excelRange = null;//Excel Range Object,多种用途
private Excel.Font excelFont = null;
private object opt = System.Reflection.Missing.Value;
private Excel.Range excelCopySourceRange = null;//Excel Range Object
private int excelActiveWorkSheetIndex; //活动工作表索引
private string excelOpenFileName;
private string excelSaveFileName;
private string excelTempName;
private string path; //add by Steven on Step 18, 2008
private string filePath = "";
#endregion
#region Properties
public int ActiveSheetIndex
{
get
{
return excelActiveWorkSheetIndex;
}
set
{
excelActiveWorkSheetIndex = value;
}
}
public string OpenFileName
{
get
{
return excelOpenFileName;
}
set
{
excelOpenFileName = value;
}
}
public string SaveFileName
{
get
{
return excelSaveFileName;
}
set
{
excelSaveFileName = value;
}
}
public string TempName
{
get { return excelTempName; }
set { excelTempName = value; }
}
public bool Visible
{
get
{
return excelApplication.Visible;
}
set
{
excelApplication.Visible = value;
}
}
public string ExcelOpenFileName
{
get { return excelOpenFileName; }
}
#endregion
/// <summary>
/// Construtor
/// </summary>
/// <param name="templateFile">template excel file</param>
/// <param name="savePath">save path</param>
public ExcelLib(string templateFile, string saveDir)//Guoxin update savePath to saveDir to make it a clear meaning
{
this.path = templateFile;
//excelOpenFileName = path; //modify by Steven on Step 18, 2008, because it does not allow to be operated by more than one at the same time.
excelApplication = null;//Excel Application Object
excelWorkBooks = null;//Workbooks
excelWorkBook = null;//Excel Workbook Object
excelWorkSheet = null;//Excel Worksheet Object
ActiveSheetIndex = 1; //默认值活动工作簿为第一个;设置活动工作簿请参阅SetActiveWorkSheet()
filePath = saveDir;
}
//Added by MZ
public void CreateExcelFileByTemplate(string excelFileName, bool overwrite)
{
if (string.IsNullOrEmpty(this.path))
{
throw new Exception("Template excel file can not be found.");
}
if (!System.IO.Directory.Exists(filePath))
{
System.IO.Directory.CreateDirectory(filePath);
}
try
{
string newOpenFileName = filePath + excelFileName;
this.excelOpenFileName = newOpenFileName;
this.excelSaveFileName = newOpenFileName;
//Copy the template to another place to allow to use unique one for every operation.
System.IO.File.Copy(this.path, newOpenFileName, overwrite);
}
catch
{
throw;
}
if (!File.Exists(excelOpenFileName))
{
throw new Exception(excelOpenFileName + "can not be found.");//
}
InitExcelApp();
}
public void OpenExcelFile(string fileName)
{
if (string.IsNullOrEmpty(fileName) ||
!fileName.ToLower().EndsWith(@".xls"))
{
throw new Exception("Invalid excel file name.");
}
if (!File.Exists(fileName))
{
throw new Exception(fileName + " can not be found.");
}
this.excelOpenFileName = fileName;
this.excelSaveFileName = fileName;
InitExcelApp();
}
/// <summary>
/// Create excel file
/// </summary>
/// <param name="sheetName">sheetname</param>
public void CreateExcelFile(string sheetName)
{
int temp;
temp = System.Convert.ToInt32(System.DateTime.Now.Millisecond.ToString());
System.Random ra = new System.Random(temp);
int TmpNumber = ra.Next();
if (!System.IO.Directory.Exists(filePath))
{
System.IO.Directory.CreateDirectory(filePath);
}
//add by steven
try
{
//Copy the template to another place to allow to use unique one for every operation.
excelTempName = System.Convert.ToString(TmpNumber) + "temp.xls";
string newOpenFileName = filePath + excelTempName;
excelOpenFileName = newOpenFileName;
System.IO.File.Copy(this.path, newOpenFileName);
}
catch (Exception e)
{
}
if (!File.Exists(excelOpenFileName))
{
throw new Exception(excelOpenFileName + "cant' be found.");//
}
//**************************************************
excelSaveFileName = filePath + System.Convert.ToString(TmpNumber) + ".xls";
CreateSheet(sheetName);
}
public void ActiveSheet(int index)
{
excelWorkSheets = (Excel.Sheets)excelWorkBook.Worksheets;
excelWorkSheet = (Excel.Worksheet)(excelWorkSheets.get_Item(index));
}
public void SelectSheet(int index)
{
}
public void ActiveSheet(string sheetName)
{
excelWorkSheets = (Excel.Sheets)excelWorkBook.Worksheets;
excelWorkSheet = (Excel.Worksheet)(excelWorkSheets.get_Item(sheetName));
}
public bool HasSheet(object index)
{
try
{
excelWorkSheets = (Excel.Sheets)excelWorkBook.Worksheets;
object temp = excelWorkSheets.get_Item(index);
if (object.Equals(temp, null))
{
return false;
}
}
catch
{
return false;
}
return true;
}
private void CreateSheet(string sheetName)
{
excelApplication = new Excel.ApplicationClass();
excelWorkBooks = (Excel.Workbooks)excelApplication.Workbooks;
excelWorkBook = (Excel.Workbook)(excelWorkBooks.Open(excelOpenFileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value));
// Add data to cells in the first worksheet in the new workbook.
excelWorkSheets = (Excel.Sheets)excelWorkBook.Worksheets;
excelWorkSheet = (Excel.Worksheet)(excelWorkSheets.get_Item(1));
excelWorkSheet.Name = sheetName;
}
private void InitExcelApp()
{
try
{
excelApplication = new Excel.ApplicationClass();
excelWorkBooks = (Excel.Workbooks)excelApplication.Workbooks;
excelWorkBook = (Excel.Workbook)(excelWorkBooks.Open(excelOpenFileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value));
//excelApplication.Visible = true;
}
catch
{
CloseExcelApplication();
throw;
}
}
/// <summary>
/// 返回一个ExcelRange
/// </summary>
/// <param name="startCell">开始单元格</param>
/// <param name="endCell">结束单元格,可为空,为空则返回单个单无格</param>
/// <returns></returns>
public Excel.Range getRange(string startCell, string endCell)
{
if (endCell == "")
{
return excelWorkSheet.get_Range(startCell, opt);
}
else
{
return excelWorkSheet.get_Range(startCell, endCell);
}
}
//add by MZ
public void SetHyperlink(Excel.Range range, string strAddress, string strDisplayText)
{
excelWorkSheet.Hyperlinks.Add(range, strAddress, Missing.Value, strAddress, strDisplayText);
}
public void SetHyperlink(int cellRowID, int cellColumnID, string strAddress, string strDisplayText)
{
string startCell = "";
startCell = ConvertColumnToCapital(cellColumnID) + cellRowID.ToString();
Excel.Range range = getRange(startCell, "");
SetHyperlink(range, strAddress, strDisplayText);
}
/// <summary>
/// 写入一个分页符
/// </summary>
/// <returns></returns>
public void insertPageBreak(Excel.Range range)
{
range.PageBreak = 1;
}
/// <summary>
/// 读取一个Cell的值
/// </summary>
/// <param name="CellRowID">要读取的Cell的行索引</param>
/// <param name="CellColumnID">要读取的Cell的列索引</param>
/// <returns>Cell的值</returns>
public string getOneCellValue(int CellRowID, int CellColumnID)
{
if (CellRowID <= 0)
{
throw new Exception("Invalid row index");
}
string sValue = "";
try
{
sValue = ((Excel.Range)excelWorkSheet.Cells[CellRowID, CellColumnID]).Text.ToString();
}
catch (Exception e)
{
CloseExcelApplication();
//throw new Exception(e.Message);
}
return (sValue);
}
/// <summary>
/// 读取一个连续区域的Cell的值(矩形区域,包含一行或一列,或多行,多列),返回一个一维字符串数组。
/// </summary>
/// <param name="StartCell">StartCell是要写入区域的左上角单元格</param>
/// <param name="EndCell">EndCell是要写入区域的右下角单元格</param>
/// <returns>值的集合</returns>
public string[] getCellsValue(string StartCell, string EndCell)
{
string[] sValue = null;
excelRange = (Excel.Range)excelWorkSheet.get_Range(StartCell, EndCell);
sValue = new string[excelRange.Count];
int rowStartIndex = ((Excel.Range)excelWorkSheet.get_Range(StartCell, StartCell)).Row; //起始行号
int columnStartIndex = ((Excel.Range)excelWorkSheet.get_Range(StartCell, StartCell)).Column; //起始列号
int rowNum = excelRange.Rows.Count; //行数目
int columnNum = excelRange.Columns.Count; //列数目
int index = 0;
for (int i = rowStartIndex; i < rowStartIndex + rowNum; i++)
{
for (int j = columnStartIndex; j < columnNum + columnStartIndex; j++)
{
//读到空值null和读到空串""分别处理
sValue[index] = ((Excel.Range)excelWorkSheet.Cells[i, j]).Text.ToString();
index++;
}
}
return (sValue);
}
/// <summary>
/// 读取所有单元格的数据(矩形区域),返回一个datatable.假设所有单元格靠工作表左上区域。
/// </summary>
public System.Data.DataTable getAllCellsValue()
{
int columnCount = getTotalColumnCount();
int rowCount = getTotalRowCount();
System.Data.DataTable dt = new System.Data.DataTable();
//设置datatable列的名称
for (int columnID = 1; columnID <= columnCount; columnID++)
{
dt.Columns.Add(((Excel.Range)excelWorkSheet.Cells[1, columnID]).Text.ToString());
}
for (int rowID = 2; rowID <= rowCount; rowID++)
{
DataRow dr = dt.NewRow();
for (int columnID = 1; columnID <= columnCount; columnID++)
{
dr[columnID - 1] = ((Excel.Range)excelWorkSheet.Cells[rowID, columnID]).Text.ToString();
//读到空值null和读到空串""分别处理
}
dt.Rows.Add(dr);
}
return (dt);
}
/// <summary>
/// 当前活动工作表中有效行数(总行数)
/// </summary>
/// <returns></returns>
public int getTotalRowCount()
{
int rowsNumber = 0;
try
{
while (true)
{
if (((Excel.Range)excelWorkSheet.Cells[rowsNumber + 1, 1]).Text.ToString().Trim() == "" &&
((Excel.Range)excelWorkSheet.Cells[rowsNumber + 2, 1]).Text.ToString().Trim() == "" &&
((Excel.Range)excelWorkSheet.Cells[rowsNumber + 3, 1]).Text.ToString().Trim() == "")
break;
rowsNumber++;
}
}
catch
{
return -1;
}
return rowsNumber;
}
/// <summary>
/// 当前活动工作表中有效行数(总行数)
/// </summary>
/// <returns></returns>
public int getTotalRowCountByColumn(int column)
{
int rowsNumber = 0;
try
{
while (true)
{
if (((Excel.Range)excelWorkSheet.Cells[rowsNumber + 1, column]).Text.ToString().Trim() == "" &&
((Excel.Range)excelWorkSheet.Cells[rowsNumber + 2, column]).Text.ToString().Trim() == "" &&
((Excel.Range)excelWorkSheet.Cells[rowsNumber + 3, column]).Text.ToString().Trim() == "")
break;
rowsNumber++;
}
}
catch
{
return -1;
}
return rowsNumber;
}
/// <summary>
/// 当前活动工作表中有效列数(总列数)
/// </summary>
/// <param></param>
public int getTotalColumnCount()
{
int columnNumber = 0;
try
{
while (true)
{
if (((Excel.Range)excelWorkSheet.Cells[1, columnNumber + 1]).Text.ToString().Trim() == "" &&
((Excel.Range)excelWorkSheet.Cells[1, columnNumber + 2]).Text.ToString().Trim() == "" &&
((Excel.Range)excelWorkSheet.Cells[1, columnNumber + 3]).Text.ToString().Trim() == "")
break;
columnNumber++;
}
}
catch
{
return -1;
}
return columnNumber;
}
/// <summary>
/// 向一个Cell写入数据
/// </summary>
/// <param name="CellRowID">CellRowID是cell的行索引</param>
/// <param name="CellColumnID">CellColumnID是cell的列索引</param>
///<param name="Value">要写入该单元格的数据值</param>
public void SetOneCellValue(int CellRowID, int CellColumnID, string Value)
{
try
{
excelRange = (Excel.Range)excelWorkSheet.Cells[CellRowID, CellColumnID];
excelRange.Value2 = Value;//Value2?
//Gets or sets the value of the NamedRange control.
//The only difference between this property and the Value property is that Value2 is not a parameterized property.
excelRange = null;
}
catch (Exception e)
{
CloseExcelApplication();
//throw new Exception(e.Message);
}
}
public void SetOneCellValue(string cell, string Value)
{
excelRange = (My.Excel9.Interop.Range)excelWorkSheet.get_Range(cell, cell);
excelRange.Value2 = Value;
}
public void SetOneCellValue(int CellRowID, int CellColumnID, decimal? Value)
{
try
{
excelRange = (Excel.Range)excelWorkSheet.Cells[CellRowID, CellColumnID];
excelRange.FormulaR1C1 = Value;//Value2?
//Gets or sets the value of the NamedRange control.
//The only difference between this property and the Value property is that Value2 is not a parameterized property.
excelRange = null;
}
catch (Exception e)
{
CloseExcelApplication();
//throw new Exception(e.Message);
}
}
/// <summary>
/// 设置活动工作表
/// </summary>
/// <param name="SheetIndex">要设置为活动工作表的索引值</param>
public void SetActiveWorkSheet(int SheetIndex)
{
if (SheetIndex <= 0)
{
throw new Exception("Invalid sheet index.");
}
try
{
ActiveSheetIndex = SheetIndex;
excelWorkSheet = (Excel.Worksheet)excelWorkBook.Worksheets[ActiveSheetIndex];
}
catch (Exception e)
{
CloseExcelApplication();
// throw new Exception(e.Message);
}
}
/// <summary>
/// 向连续区域一次性写入数据;只有在区域连续和写入的值相同的情况下可以使用方法
/// </summary>
/// <param name="StartCell">StartCell是要写入区域的左上角单元格</param>
/// <param name="EndCell">EndCell是要写入区域的右下角单元格</param>
/// <param name="Value">要写入指定区域所有单元格的数据值</param>
public void setCellsValue(string StartCell, string EndCell, string Value)
{
try
{
excelRange = excelWorkSheet.get_Range(StartCell, EndCell);
excelRange.Value2 = Value;
excelRange = null;
}
catch (Exception e)
{
CloseExcelApplication();
//throw new Exception(e.Message);
}
}
/// <summary>
/// 给一行写数据
/// </summary>
public void setOneLineValues(int LineID, int StartCellColumnID, int EndCellColumnID, string[] Values)////已经测试
{
//用1-19号元素
//if (Values.Length!=EndCellColumnID-StartCellColumnID)
//{
// throw new Exception("单元格数目与提供的值的数目不一致!");
//}
int j = 0;
for (int i = StartCellColumnID; i <= EndCellColumnID; i++)
{
if (j < Values.Length)
{
SetOneCellValue(LineID, i, Values[j]);
j += 1;
}
}
}
public void setOneLineValues(int LineID, int StartCellColumnID, int EndCellColumnID, int skip, string[] Values)////已经测试
{
//用1-19号元素
//if (Values.Length!=EndCellColumnID-StartCellColumnID)
//{
// throw new Exception("单元格数目与提供的值的数目不一致!");
//}
int j = 0;
for (int i = StartCellColumnID; i <= EndCellColumnID; i += skip)
{
if (j < Values.Length)
{
SetOneCellValue(LineID, i, Values[j]);
j += 1;
}
}
}
public void SetRangeValues(int startRow, int startColumn, int endRow, int endColumn, string[,] content)
{
excelRange = excelWorkSheet.get_Range(excelWorkSheet.Cells[startRow, startColumn], excelWorkSheet.Cells[endRow, endColumn]);
excelRange.Value2 = content;
}
/// <summary>
/// 设置单元格的边框格式
/// </summary>
/// <param name="startCell">开始位置</param>
/// <param name="endCell">结束位置,为空则设置单个单元格</param>
/// <param name="borderStyle">边框形式,Top,Left,Right,Bottom,All,</param>
/// <param name="lineStyle">线样式,Continuous,Dash,Dot,Double,None,Outer</param>
/// <param name="bold">是否粗边框</param>
public void setCellsBorder(string startCell, string endCell, string borderStyle, string lineStyle, bool bold)
{
Excel.Range range = getRange(startCell, endCell);
switch (borderStyle)
{
case "Top":
switch (lineStyle)
{
case "Continuous":
range.Borders[Excel.XlBordersIndex.xlEdgeTop].LineStyle = Excel.XlLineStyle.xlContinuous;
range.Borders[Excel.XlBordersIndex.xlEdgeTop].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeTop].ColorIndex = -4105;
break;
case "Dash":
range.Borders[Excel.XlBordersIndex.xlEdgeTop].LineStyle = Excel.XlLineStyle.xlDash;
range.Borders[Excel.XlBordersIndex.xlEdgeTop].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeTop].ColorIndex = -4105;
break;
case "xlDot":
range.Borders[Excel.XlBordersIndex.xlEdgeTop].LineStyle = Excel.XlLineStyle.xlDot;
range.Borders[Excel.XlBordersIndex.xlEdgeTop].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeTop].ColorIndex = -4105;
break;
case "xlDouble":
range.Borders[Excel.XlBordersIndex.xlEdgeTop].LineStyle = Excel.XlLineStyle.xlDouble;
range.Borders[Excel.XlBordersIndex.xlEdgeTop].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeTop].ColorIndex = -4105;
break;
case "None":
range.Borders[Excel.XlBordersIndex.xlEdgeTop].LineStyle = Excel.XlLineStyle.xlLineStyleNone;
range.Borders[Excel.XlBordersIndex.xlEdgeTop].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeTop].ColorIndex = -4105;
break;
}
break;
case "Left":
switch (lineStyle)
{
case "Continuous":
range.Borders[Excel.XlBordersIndex.xlEdgeLeft].LineStyle = Excel.XlLineStyle.xlContinuous;
range.Borders[Excel.XlBordersIndex.xlEdgeLeft].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeLeft].ColorIndex = -4105;
break;
case "Dash":
range.Borders[Excel.XlBordersIndex.xlEdgeLeft].LineStyle = Excel.XlLineStyle.xlDash;
range.Borders[Excel.XlBordersIndex.xlEdgeLeft].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeLeft].ColorIndex = -4105;
break;
case "xlDot":
range.Borders[Excel.XlBordersIndex.xlEdgeLeft].LineStyle = Excel.XlLineStyle.xlDot;
range.Borders[Excel.XlBordersIndex.xlEdgeLeft].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeLeft].ColorIndex = -4105;
break;
case "xlDouble":
range.Borders[Excel.XlBordersIndex.xlEdgeLeft].LineStyle = Excel.XlLineStyle.xlDouble;
range.Borders[Excel.XlBordersIndex.xlEdgeLeft].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeLeft].ColorIndex = -4105;
break;
case "None":
range.Borders[Excel.XlBordersIndex.xlEdgeLeft].LineStyle = Excel.XlLineStyle.xlLineStyleNone;
range.Borders[Excel.XlBordersIndex.xlEdgeLeft].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeLeft].ColorIndex = -4105;
break;
}
break;
case "Right":
switch (lineStyle)
{
case "Continuous":
range.Borders[Excel.XlBordersIndex.xlEdgeRight].LineStyle = Excel.XlLineStyle.xlContinuous;
range.Borders[Excel.XlBordersIndex.xlEdgeRight].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeRight].ColorIndex = -4105;
break;
case "Dash":
range.Borders[Excel.XlBordersIndex.xlEdgeRight].LineStyle = Excel.XlLineStyle.xlDash;
range.Borders[Excel.XlBordersIndex.xlEdgeRight].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeRight].ColorIndex = -4105;
break;
case "xlDot":
range.Borders[Excel.XlBordersIndex.xlEdgeRight].LineStyle = Excel.XlLineStyle.xlDot;
range.Borders[Excel.XlBordersIndex.xlEdgeRight].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeRight].ColorIndex = -4105;
break;
case "xlDouble":
range.Borders[Excel.XlBordersIndex.xlEdgeRight].LineStyle = Excel.XlLineStyle.xlDouble;
range.Borders[Excel.XlBordersIndex.xlEdgeRight].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeRight].ColorIndex = -4105;
break;
case "None":
range.Borders[Excel.XlBordersIndex.xlEdgeRight].LineStyle = Excel.XlLineStyle.xlLineStyleNone;
range.Borders[Excel.XlBordersIndex.xlEdgeRight].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeRight].ColorIndex = -4105;
break;
}
break;
case "Bottom":
switch (lineStyle)
{
case "Continuous":
range.Borders[Excel.XlBordersIndex.xlEdgeBottom].LineStyle = Excel.XlLineStyle.xlContinuous;
range.Borders[Excel.XlBordersIndex.xlEdgeBottom].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeBottom].ColorIndex = -4105;
break;
case "Dash":
range.Borders[Excel.XlBordersIndex.xlEdgeBottom].LineStyle = Excel.XlLineStyle.xlDash;
range.Borders[Excel.XlBordersIndex.xlEdgeBottom].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeBottom].ColorIndex = -4105;
break;
case "xlDot":
range.Borders[Excel.XlBordersIndex.xlEdgeBottom].LineStyle = Excel.XlLineStyle.xlDot;
range.Borders[Excel.XlBordersIndex.xlEdgeBottom].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeBottom].ColorIndex = -4105;
break;
case "xlDouble":
range.Borders[Excel.XlBordersIndex.xlEdgeBottom].LineStyle = Excel.XlLineStyle.xlDouble;
range.Borders[Excel.XlBordersIndex.xlEdgeBottom].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeBottom].ColorIndex = -4105;
break;
case "None":
range.Borders[Excel.XlBordersIndex.xlEdgeBottom].LineStyle = Excel.XlLineStyle.xlLineStyleNone;
range.Borders[Excel.XlBordersIndex.xlEdgeBottom].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeBottom].ColorIndex = -4105;
break;
}
break;
case "All":
switch (lineStyle)
{
case "Continuous":
range.Borders[Excel.XlBordersIndex.xlDiagonalDown].LineStyle = -4142;
range.Borders[Excel.XlBordersIndex.xlDiagonalUp].LineStyle = -4142;
range.Borders[Excel.XlBordersIndex.xlEdgeTop].LineStyle = Excel.XlLineStyle.xlContinuous;
range.Borders[Excel.XlBordersIndex.xlEdgeTop].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeTop].ColorIndex = -4105;
range.Borders[Excel.XlBordersIndex.xlEdgeLeft].LineStyle = Excel.XlLineStyle.xlContinuous;
range.Borders[Excel.XlBordersIndex.xlEdgeLeft].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeLeft].ColorIndex = -4105;
range.Borders[Excel.XlBordersIndex.xlEdgeRight].LineStyle = Excel.XlLineStyle.xlContinuous;
range.Borders[Excel.XlBordersIndex.xlEdgeRight].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeRight].ColorIndex = -4105;
range.Borders[Excel.XlBordersIndex.xlEdgeBottom].LineStyle = Excel.XlLineStyle.xlContinuous;
range.Borders[Excel.XlBordersIndex.xlEdgeBottom].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeBottom].ColorIndex = -4105;
range.Borders[Excel.XlBordersIndex.xlInsideVertical].LineStyle = Excel.XlLineStyle.xlContinuous;
range.Borders[Excel.XlBordersIndex.xlInsideVertical].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlInsideVertical].ColorIndex = -4105;
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle = Excel.XlLineStyle.xlContinuous;
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].ColorIndex = -4105;
break;
case "Dash":
range.Borders[Excel.XlBordersIndex.xlDiagonalDown].LineStyle = -4142;
range.Borders[Excel.XlBordersIndex.xlDiagonalUp].LineStyle = -4142;
range.Borders[Excel.XlBordersIndex.xlEdgeTop].LineStyle = Excel.XlLineStyle.xlDash;
range.Borders[Excel.XlBordersIndex.xlEdgeTop].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeTop].ColorIndex = -4105;
range.Borders[Excel.XlBordersIndex.xlEdgeLeft].LineStyle = Excel.XlLineStyle.xlDash;
range.Borders[Excel.XlBordersIndex.xlEdgeLeft].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeLeft].ColorIndex = -4105;
range.Borders[Excel.XlBordersIndex.xlEdgeRight].LineStyle = Excel.XlLineStyle.xlDash;
range.Borders[Excel.XlBordersIndex.xlEdgeRight].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeRight].ColorIndex = -4105;
range.Borders[Excel.XlBordersIndex.xlEdgeBottom].LineStyle = Excel.XlLineStyle.xlDash;
range.Borders[Excel.XlBordersIndex.xlEdgeBottom].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeBottom].ColorIndex = -4105;
range.Borders[Excel.XlBordersIndex.xlInsideVertical].LineStyle = Excel.XlLineStyle.xlDash;
range.Borders[Excel.XlBordersIndex.xlInsideVertical].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlInsideVertical].ColorIndex = -4105;
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle = Excel.XlLineStyle.xlDash;
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].ColorIndex = -4105;
break;
case "xlDot":
range.Borders[Excel.XlBordersIndex.xlDiagonalDown].LineStyle = -4142;
range.Borders[Excel.XlBordersIndex.xlDiagonalUp].LineStyle = -4142;
range.Borders[Excel.XlBordersIndex.xlEdgeTop].LineStyle = Excel.XlLineStyle.xlDot;
range.Borders[Excel.XlBordersIndex.xlEdgeTop].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeTop].ColorIndex = -4105;
range.Borders[Excel.XlBordersIndex.xlEdgeLeft].LineStyle = Excel.XlLineStyle.xlDot;
range.Borders[Excel.XlBordersIndex.xlEdgeLeft].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeLeft].ColorIndex = -4105;
range.Borders[Excel.XlBordersIndex.xlEdgeRight].LineStyle = Excel.XlLineStyle.xlDot;
range.Borders[Excel.XlBordersIndex.xlEdgeRight].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeRight].ColorIndex = -4105;
range.Borders[Excel.XlBordersIndex.xlEdgeBottom].LineStyle = Excel.XlLineStyle.xlDot;
range.Borders[Excel.XlBordersIndex.xlEdgeBottom].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeBottom].ColorIndex = -4105;
range.Borders[Excel.XlBordersIndex.xlInsideVertical].LineStyle = Excel.XlLineStyle.xlDot;
range.Borders[Excel.XlBordersIndex.xlInsideVertical].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlInsideVertical].ColorIndex = -4105;
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle = Excel.XlLineStyle.xlDot;
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].ColorIndex = -4105;
break;
case "xlDouble":
range.Borders[Excel.XlBordersIndex.xlDiagonalDown].LineStyle = -4142;
range.Borders[Excel.XlBordersIndex.xlDiagonalUp].LineStyle = -4142;
range.Borders[Excel.XlBordersIndex.xlEdgeTop].LineStyle = Excel.XlLineStyle.xlDouble;
range.Borders[Excel.XlBordersIndex.xlEdgeTop].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeTop].ColorIndex = -4105;
range.Borders[Excel.XlBordersIndex.xlEdgeLeft].LineStyle = Excel.XlLineStyle.xlDouble;
range.Borders[Excel.XlBordersIndex.xlEdgeLeft].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeLeft].ColorIndex = -4105;
range.Borders[Excel.XlBordersIndex.xlEdgeRight].LineStyle = Excel.XlLineStyle.xlDouble;
range.Borders[Excel.XlBordersIndex.xlEdgeRight].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeRight].ColorIndex = -4105;
range.Borders[Excel.XlBordersIndex.xlEdgeBottom].LineStyle = Excel.XlLineStyle.xlDouble;
range.Borders[Excel.XlBordersIndex.xlEdgeBottom].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeBottom].ColorIndex = -4105;
range.Borders[Excel.XlBordersIndex.xlInsideVertical].LineStyle = Excel.XlLineStyle.xlDouble;
range.Borders[Excel.XlBordersIndex.xlInsideVertical].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlInsideVertical].ColorIndex = -4105;
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle = Excel.XlLineStyle.xlDouble;
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].ColorIndex = -4105;
break;
case "None":
range.Borders[Excel.XlBordersIndex.xlDiagonalDown].LineStyle = -4142;
range.Borders[Excel.XlBordersIndex.xlDiagonalUp].LineStyle = -4142;
range.Borders[Excel.XlBordersIndex.xlEdgeTop].LineStyle = Excel.XlLineStyle.xlLineStyleNone;
range.Borders[Excel.XlBordersIndex.xlEdgeTop].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeTop].ColorIndex = -4105;
range.Borders[Excel.XlBordersIndex.xlEdgeLeft].LineStyle = Excel.XlLineStyle.xlLineStyleNone;
range.Borders[Excel.XlBordersIndex.xlEdgeLeft].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeLeft].ColorIndex = -4105;
range.Borders[Excel.XlBordersIndex.xlEdgeRight].LineStyle = Excel.XlLineStyle.xlLineStyleNone;
range.Borders[Excel.XlBordersIndex.xlEdgeRight].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeRight].ColorIndex = -4105;
range.Borders[Excel.XlBordersIndex.xlEdgeBottom].LineStyle = Excel.XlLineStyle.xlLineStyleNone;
range.Borders[Excel.XlBordersIndex.xlEdgeBottom].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeBottom].ColorIndex = -4105;
range.Borders[Excel.XlBordersIndex.xlInsideVertical].LineStyle = Excel.XlLineStyle.xlLineStyleNone;
range.Borders[Excel.XlBordersIndex.xlInsideVertical].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlInsideVertical].ColorIndex = -4105;
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle = Excel.XlLineStyle.xlLineStyleNone;
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].ColorIndex = -4105;
break;
case "Outer":
range.Borders[Excel.XlBordersIndex.xlDiagonalDown].LineStyle = -4142;
range.Borders[Excel.XlBordersIndex.xlDiagonalUp].LineStyle = -4142;
range.Borders[Excel.XlBordersIndex.xlEdgeTop].LineStyle = Excel.XlLineStyle.xlContinuous;
range.Borders[Excel.XlBordersIndex.xlEdgeTop].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeTop].ColorIndex = -4105;
range.Borders[Excel.XlBordersIndex.xlEdgeLeft].LineStyle = Excel.XlLineStyle.xlContinuous;
range.Borders[Excel.XlBordersIndex.xlEdgeLeft].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeLeft].ColorIndex = -4105;
range.Borders[Excel.XlBordersIndex.xlEdgeRight].LineStyle = Excel.XlLineStyle.xlContinuous;
range.Borders[Excel.XlBordersIndex.xlEdgeRight].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeRight].ColorIndex = -4105;
range.Borders[Excel.XlBordersIndex.xlEdgeBottom].LineStyle = Excel.XlLineStyle.xlContinuous;
range.Borders[Excel.XlBordersIndex.xlEdgeBottom].Weight = bold ? -4138 : 2;
range.Borders[Excel.XlBordersIndex.xlEdgeBottom].ColorIndex = -4105;
break;
}
break;
}
}
public void setCellsBorder(string startCell, string endCell)
{
//设置某个范围内的单元格的边框
excelRange = excelWorkSheet.get_Range(startCell, endCell);
excelRange.Borders[Excel.XlBordersIndex.xlEdgeLeft].LineStyle = Excel.XlLineStyle.xlContinuous;
excelRange.Borders[Excel.XlBordersIndex.xlEdgeTop].LineStyle = Excel.XlLineStyle.xlContinuous;
excelRange.Borders[Excel.XlBordersIndex.xlEdgeRight].LineStyle = Excel.XlLineStyle.xlContinuous;
excelRange.Borders[Excel.XlBordersIndex.xlEdgeBottom].LineStyle = Excel.XlLineStyle.xlContinuous;
excelRange.Borders[Excel.XlBordersIndex.xlInsideVertical].LineStyle = Excel.XlLineStyle.xlContinuous;
//excelRange.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle = Excel.XlLineStyle.xlContinuous;
}
public void setOneCellBorder(int CellRowID, int CellColumnID)
{
//设置某个单元格的边框
excelRange = (Excel.Range)excelWorkSheet.Cells[CellRowID, CellColumnID];
excelRange.Borders[Excel.XlBordersIndex.xlEdgeLeft].LineStyle = Excel.XlLineStyle.xlContinuous;
excelRange.Borders[Excel.XlBordersIndex.xlEdgeTop].LineStyle = Excel.XlLineStyle.xlContinuous;
excelRange.Borders[Excel.XlBordersIndex.xlEdgeRight].LineStyle = Excel.XlLineStyle.xlContinuous;
excelRange.Borders[Excel.XlBordersIndex.xlEdgeBottom].LineStyle = Excel.XlLineStyle.xlContinuous;
//excelRange.Borders[Excel.XlBordersIndex.xlInsideVertical].LineStyle = Excel.XlLineStyle.xlContinuous;
//excelRange.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle = Excel.XlLineStyle.xlContinuous;
}
public void SetColumnWidth(string startCell, string endCell, int size)
{
//设置某个范围内的单元格的列的宽度
excelRange = excelWorkSheet.get_Range(startCell, endCell);
excelRange.ColumnWidth = size;
}
public void SetOneCellFont(int CellRowID, int CellColumnID, string fontName, int fontSize)
{
excelRange = (Excel.Range)excelWorkSheet.Cells[CellRowID, CellColumnID];
excelRange.Font.Name = fontName;
excelRange.Font.Size = fontSize;
}
public void SetOneCellHorizontalAlignment(int CellRowID, int CellColumnID, Excel.Constants alignment)
{
excelRange = (Excel.Range)excelWorkSheet.Cells[CellRowID, CellColumnID];
excelRange.HorizontalAlignment = alignment;
}
public void SetOneCellColumnWidth(int CellRowID, int CellColumnID, int size)
{
//设置某个单元格的列的宽度
excelRange = (Excel.Range)excelWorkSheet.Cells[CellRowID, CellColumnID];
excelRange.ColumnWidth = size;
}
/// <summary>
/// 设置一个Cell的数据格式
/// </summary>
/// <param name="CellRowID">CellRowID是cell的行索引</param>
/// <param name="CellColumnID">CellColumnID是cell的列索引</param>
///<param name="Value">数据格式</param>
public void setOneCellNumberFormat(int CellRowID, int CellColumnID, string numberFormat)
{
try
{
excelRange = (Excel.Range)excelWorkSheet.Cells[CellRowID, CellColumnID];
excelRange.NumberFormatLocal = numberFormat;
excelRange = null;
}
catch (Exception e)
{
CloseExcelApplication();
//throw new Exception(e.Message);
}
}
public void SetRowHeight(string startCell, string endCell, int size)
{
//设置某个范围内的单元格的行的高度
excelRange = excelWorkSheet.get_Range(startCell, endCell);
excelRange.RowHeight = size;
}
public void SetRowHeight(int CellRowID, int CellColumnID, float size)
{
//设置某个范围内的单元格的行的高度
excelRange = (Excel.Range)excelWorkSheet.Cells[CellRowID, CellColumnID];
excelRange.RowHeight = size;
}
public void SetOneCellRowHeight(int CellRowID, int CellColumnID, int size)
{
//设置某个单元格的行的高度
excelRange = (Excel.Range)excelWorkSheet.Cells[CellRowID, CellColumnID];
excelRange.RowHeight = size;
}
/// <summary>
/// 拷贝区域.限制:在同一个工作表中复制
/// </summary>
/// <param name="SourceStart">源区域的左上角单元格</param>
/// <param name="SourceEnd">源区域的右下角单元格</param>
/// <param name="DesStart">目标区域的左上角单元格</param>
/// <param name="DesEnd">目标区域的右下角单元格</param>
public void CopyCells(string SourceStart, string SourceEnd, string DesStart, string DesEnd)
{
try
{
excelCopySourceRange = excelWorkSheet.get_Range(SourceStart, SourceEnd);
excelRange = excelWorkSheet.get_Range(DesStart, DesEnd);
excelCopySourceRange.Copy(excelRange);
excelCopySourceRange = null;
excelRange = null;
}
catch (Exception e)
{
CloseExcelApplication();
//throw new Exception(e.Message);
}
}
public void CopyWorksheet(int SourceWorksheetIndex, int DesWorksheetIndex)
{
try
{
//Sheets("Sheet2").Copy After:=Sheets(3)
Excel.Worksheet sheetSource = (Excel.Worksheet)excelWorkBook.Worksheets[SourceWorksheetIndex];
sheetSource.Select(Missing.Value);
Excel.Worksheet sheetDest = (Excel.Worksheet)excelWorkBook.Worksheets[DesWorksheetIndex];
sheetSource.Copy(Missing.Value, sheetDest);
}
catch (Exception e)
{
CloseExcelApplication();
//throw new Exception(e.Message);
}
}
/// <summary>
/// 插入一行
/// </summary>
/// <param name="CellRowID">要插入所在行的索引位置,插入后其原有行下移</param>
/// <param name="RowNum">要插入行的个数</param>
public void InsertRow(int CellRowID, int RowNum)//插入空行
{
if (CellRowID <= 0)
{
throw new Exception("Invalid row index.");
}
if (RowNum <= 0)
{
throw new Exception("Invalid row number.");
}
try
{
excelRange = (Excel.Range)excelWorkSheet.Rows[CellRowID, Missing.Value];
for (int i = 0; i < RowNum; i++)
{
excelRange.Insert(Excel.XlDirection.xlDown);
//excelRange.Interior.ColorIndex = 0;
}
excelRange = null;
}
catch (Exception e)
{
CloseExcelApplication();
//throw new Exception(e.Message);
}
}
public void InsertCol(int CellColID, int ColNum)
{
if (CellColID <= 0)
{
throw new Exception("Invalid column index.");
}
if (ColNum <= 0)
{
throw new Exception("Invalid column number.");
}
try
{
excelRange = (Excel.Range)excelWorkSheet.Columns[CellColID, Missing.Value];
for (int i = 0; i < ColNum; i++)
{
excelRange.Insert(Excel.XlDirection.xlToRight);
//excelRange.Interior.ColorIndex = 0;
}
excelRange = null;
}
catch (Exception e)
{
CloseExcelApplication();
//throw new Exception(e.Message);
}
}
public void DeleteRow(int rowID)
{
if (rowID <= 0)
{
throw new Exception("Invalid row index.");
}
try
{
excelRange = (Excel.Range)excelWorkSheet.Rows[rowID, Missing.Value];
excelRange.Delete(Excel.XlDirection.xlUp);
excelRange = null;
}
catch
{
CloseExcelApplication();
}
}
public Excel.Range FindFirstRange(Excel.Range xlRange, string FindText)//查找
{
//查找第一个满足的区域
//Search for the first match
Excel.Range firstFind = null;
firstFind = xlRange.Find(FindText, Missing.Value, Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart, Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext, false,Missing.Value);
return firstFind; //如果没找到,返回空
}
public Excel.Range FindFirstRange(string startCell, string endCell, string FindText)//查找
{
Excel.Range range = getRange(startCell, endCell);
return FindFirstRange(range, FindText);
}
public int[] FindFirstRangePosition(string startCell, string endCell, string FindText)
{
int[] position = { -1, -1 };
Excel.Range cell = FindFirstRange(startCell, endCell, FindText);
if (cell != null)
{
position[0] = cell.Row;
position[1] = cell.Column;
}
return position;
}
public int FindFirstRangeRowNo(string startCell, string endCell, string FindText)
{
int[] position = FindFirstRangePosition(startCell, endCell, FindText);
return position[0];
}
public int FindFirstRangeColumnNo(string startCell, string endCell, string FindText)
{
int[] position = FindFirstRangePosition(startCell, endCell, FindText);
return position[1];
}
/// <summary>
/// 判断单元格是否有数据
/// </summary>
public bool CellValueIsNull(int CellLineID, int CellColumnID)////已经测试
{
if ((((Excel.Range)excelWorkSheet.Cells[CellLineID, CellColumnID]).Text.ToString().Trim() != ""))
return false;
return true;
}
public void newWorkbook(string excelTemplate, string fileName)
{
//以excelTemplate为模板新建文件fileName
//excelApplication.
excelWorkBook = excelWorkBooks.Add(excelTemplate);
SaveFileName = "";
SaveAsExcel();
}
public void newWorksheet()
{
excelWorkBook.Worksheets.Add(Missing.Value, Missing.Value, 1, Missing.Value);
}
public void setWorksheetName(int sheetIndex, string worksheetName)
{
// Missing.Value
Excel._Worksheet sheet = (Excel._Worksheet)(excelWorkBook.Worksheets[(object)sheetIndex]);
sheet.Name = worksheetName;
}
public void mergeOneLineCells(string startCell, string endCell)
{
//合并一行单元格
excelRange = excelWorkSheet.get_Range(startCell, endCell);
//excelRange.Merge(true);
excelRange.MergeCells = true;
}
public void HorizontalAlignmentCells(string startCell, string endCell, Excel.Constants alignment)
{
//水平对齐一行单元格
excelRange = excelWorkSheet.get_Range(startCell, endCell);
excelRange.HorizontalAlignment = alignment;
}
public void VerticalAlignmentCells(string startCell, string endCell, Excel.Constants alignment)
{
//垂直对齐一行单元格
excelRange = excelWorkSheet.get_Range(startCell, endCell);
excelRange.VerticalAlignment = alignment;
}
//实现列号-〉字母 (26-〉Z,27->AA)
private string ConvertColumnIndexToChar(int columnIndex)
{
if (columnIndex < 1 || columnIndex > 256)
{
// MessageBox.Show("columnIndex=" + columnIndex + ",超出了有效范围(1-256)");
return "A";
}
if (columnIndex >= 1 && columnIndex <= 26)//1--26
{
return "AA";
}
if (columnIndex >= 27 && columnIndex <= 256)//27--256
{
return "AA";
}
return "A";
}
public string ConvertColumnToCapital(int columnID)
{
string capital = "A";
if (columnID <= 26)
{
capital = Chr(columnID + 64);
}
else if (columnID <= 52)
{
capital = "A" + Chr(columnID - 26 + 64);
}
else if (columnID <= 78)
{
capital = "B" + Chr(columnID - 52 + 64);
}
return capital;
}
private string Chr(int num)
{
return Convert.ToChar(num).ToString();
}
private int Asc(string s)
{
return Convert.ToInt16(Convert.ToChar(s));
}
/// <summary>
/// Save As
/// </summary>
public void SaveAsExcel()
{
if (string.IsNullOrEmpty(excelOpenFileName))
{
throw new Exception("Excel file name can not be empty.");
}
try
{
//excelWorkSheet.SaveAs(excelSaveFileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value);
//excelWorkSheet.SaveAs(excelSaveFileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value);
//excelWorkBook.SaveAs(excelOpenFileName, Excel.XlFileFormat.xlWorkbookNormal, opt, opt, opt, opt, Excel.XlSaveAsAccessMode.xlNoChange, opt, opt, opt, opt, opt);
excelWorkBook.SaveAs(excelOpenFileName, Excel.XlFileFormat.xlWorkbookNormal, opt, opt, opt, opt, Excel.XlSaveAsAccessMode.xlNoChange, opt, opt, opt, opt);
}
catch (Exception e)
{
CloseExcelApplication();
//throw new Exception(e.Message);
}
}
/// <summary>
/// Save
/// </summary>
public void SaveExcel()
{
if (excelSaveFileName == "")
{
throw new Exception("Excel file name can not be empty.");
}
try
{
//excelWorkSheet.SaveAs(excelSaveFileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value);
//excelWorkSheet.SaveAs(excelSaveFileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value);
//excelWorkBook.SaveAs(excelOpenFileName, Excel.XlFileFormat.xlWorkbookNormal, opt, opt, opt, opt, Excel.XlSaveAsAccessMode.xlNoChange, opt, opt, opt, opt, opt);
//excelWorkBook.SaveAs(excelSaveFileName, Excel.XlFileFormat.xlWorkbookNormal, opt, opt, opt, opt, Excel.XlSaveAsAccessMode.xlNoChange, opt, opt, opt, opt, opt);
excelWorkBook.Save();
}
catch (Exception e)
{
CloseExcelApplication();
//throw new Exception(e.Message);
}
}
/// <summary>
/// 保存Excel文件,格式xml.
/// </summary>
public void SaveExcelAsXML()
{
if (excelSaveFileName == "")
{
throw new Exception("Invalid excel file name.");
}
try
{
//excelWorkSheet.SaveAs(excelSaveFileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value);
excelWorkSheet.SaveAs(excelSaveFileName,Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value);
}
catch
{
CloseExcelApplication();
//throw new Exception(e.Message);
}
}
/// <summary>
/// 关闭Excel文件,释放对象;最后一定要调用此函数,否则会引起异常
/// </summary>
/// <param></param>
public void CloseExcelApplication()
{
try
{
excelWorkBooks = null;
excelWorkBook = null;
excelWorkSheet = null;
excelRange = null;
if (excelApplication != null)
{
excelApplication.Workbooks.Close();
//Object missing = Type.Missing;
excelApplication.Quit();
excelApplication = null;
//ReleaseAllRef(excelApplication);//Error
}
}
finally
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
private void ReleaseAllRef(Object obj)
{
//ReleaseComObject()方法可以使RCW减少一个对COM组件的引用,并返回减少一个引用后RCW对COM组件的剩余引用数量。
//我们用一个循环,就可以让RCW将所有对COM组件的引用全部去掉。
try
{
while (System.Runtime.InteropServices.Marshal.ReleaseComObject(obj) > 1) ;
}
finally
{
obj = null;
}
}
/// <summary>
/// Merge selected cells;
/// </summary>
/// <param name="startCell"></param>
/// <param name="endCell"></param>
/// <param name="horizontalAlignment"></param>
/// <param name="verticalAlignment"></param>
public void MergeCells(string startCell, string endCell, Excel.Constants horizontalAlignment, Excel.Constants verticalAlignment)
{
excelRange = excelWorkSheet.get_Range(startCell, endCell);
excelRange.HorizontalAlignment = horizontalAlignment;
excelRange.VerticalAlignment = verticalAlignment;
excelRange.Merge(false);
}
/// <summary>
/// set cells font-size
/// </summary>
/// <param name="startCell">start cell</param>
/// <param name="endCell">end cell</param>
/// <param name="fontSize">font size</param>
public void SetCellsFontSize(string startCell, string endCell, int fontSize)
{
excelRange = excelWorkSheet.get_Range(startCell, endCell);
excelRange.Font.Size = fontSize;
}
public void SetNumberFormatLocal(string startCell, string endCell, string format)
{
excelRange = excelWorkSheet.get_Range(startCell, endCell);
excelRange.NumberFormat = format;
}
/// <summary>
/// set one cell background color
/// </summary>
public void SetOneCellColor(int cellRowID, int cellColumnID, int colorIndex)
{
excelRange = (Excel.Range)excelWorkSheet.Cells[cellRowID, cellColumnID];
excelRange.Interior.ColorIndex = colorIndex;
excelRange.Interior.Pattern = Excel.Constants.xlSolid;
}
/// <summary>
/// set one cell shading color
/// </summary>
public void SetOneCellShading(int cellRowID, int cellColumnID, int colorIndex)
{
excelRange = (Excel.Range)excelWorkSheet.Cells[cellRowID, cellColumnID];
excelRange.Interior.ColorIndex = colorIndex;
excelRange.Interior.Pattern = Excel.Constants.xlSolid;
}
/// <summary>
/// set a row shading color
/// </summary>
public void SetRowShading(int rowID, int columnID, int colorIndex)
{
string startCell = "A" + rowID.ToString();
string endCell = ConvertColumnToCapital(columnID) + rowID.ToString();
excelRange = excelWorkSheet.get_Range(startCell, endCell);
excelRange.Interior.ColorIndex = colorIndex;
}
public void SetRowFontColor(int rowID, int columnID, int colorIndex)
{
string startCell = "A" + rowID.ToString();
string endCell = ConvertColumnToCapital(columnID) + rowID.ToString();
excelRange = excelWorkSheet.get_Range(startCell, endCell);
excelRange.Font.ColorIndex = colorIndex;
}
/// <summary>
/// set one cell font color(fore color)
/// </summary>
public void SetOneCellFontColor(int cellRowID, int cellColumnID, int colorIndex)
{
excelRange = (Excel.Range)excelWorkSheet.Cells[cellRowID, cellColumnID];
excelRange.Font.ColorIndex = colorIndex;
}
public void SetOneCellFontBold(int cellRowID, int cellColumnID)
{
excelRange = (Excel.Range)excelWorkSheet.Cells[cellRowID, cellColumnID];
excelRange.Font.FontStyle = "Bold";
}
/// <summary>
/// insert a picture
/// </summary>
public void InsertPicture(int cellRowID, int cellColumnID, string picturePath, int width, int height)
{
excelRange = (Excel.Range)excelWorkSheet.Cells[cellRowID, cellColumnID];
excelRange.Select();
Excel.Pictures pics = (Excel.Pictures)excelWorkSheet.Pictures(opt);
pics.Insert(picturePath, opt);
double currWith = Convert.ToDouble(excelRange.ColumnWidth);
if (currWith < ((width - 5) / 8.0))
{
excelRange.ColumnWidth = (width - 5) / 8.0;
}
excelRange.RowHeight = height * 0.75;
}
public Excel.Hyperlinks GetHyperLinks(int cellRowID, int cellColumnID)
{
List<string> links = new List<string>();
Excel.Range cell = (Excel.Range)excelWorkSheet.Cells[cellRowID, cellColumnID];
return cell.Hyperlinks;
}
public List<string> GetAllHyperLinkText(int cellRowID, int cellColumnID)
{
List<string> links = new List<string>();
Excel.Hyperlinks hyperLinks = GetHyperLinks(cellRowID, cellColumnID);
if (hyperLinks != null && hyperLinks.Count > 0)
{
foreach (Excel.Hyperlink link in hyperLinks)
{
links.Add(link.Address);
}
}
return links;
}
public string GetFirstHyperLinkText(int cellRowID, int cellColumnID)
{
Excel.Hyperlinks hyperLinks = GetHyperLinks(cellRowID, cellColumnID);
if (hyperLinks != null && hyperLinks.Count > 0)
{
return hyperLinks[1].Address;
}
return string.Empty;
}
public int GetRowCount()
{
try
{
return excelWorkSheet.UsedRange.Rows.Count;
}
catch
{
return 0;
}
}
}//end class
}
[/code]