Excel 编程中常用的对象的层次关系
Excel Application 代表整个 Microsoft Excel 应用程序,
WorkBook 代表 Microsoft Excel 工作簿
Range 代表某一单元格、某一行、某一列、某一选定区域(该区域可包含一个或若干连续单元格区域),或者某一三维区域。
Areas 选定区域内的子区域或连续单元格块的集合。
Borders 代表对象的边框。
Characters 代表包含文本的对象中的字符。可用 Characters 对象修改包含在完整文本字符串中的任意字符序列。
Font 包含对象的字体属性(字体名称、字体大小、字体颜色等)。
ListRow 代表列表对象中的一行。
Errors 表示区域的电子表格错误。
向Excel模板,指定的单元格写入数据,另存成一个excel文件
1.把Excel模板复制到最后生成Excel文件夹
string excelTemplate = runExeDir + "\\ExcelTemplate\\CcbReport.xls";
string excelReport = runExeDir + "\\CcBReport\\CcbReport.xls";
if (File.Exists(excelReport))
{
File.Delete(excelReport);
}
File.Copy(excelTemplate, excelReport);
2.读取模板的数据,读取模板数据要读取模板的Excel,如果读取复制过来的Excel模板会出现占用错误。(猜测:读完excel的时候资源不能立刻释放。)
{
string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Extended Properties=\"Excel 8.0;HDR=No;IMEX=1\";" +
"data source=" + excelTemplate;
OleDbConnection conn = new OleDbConnection(connStr);
conn.Open();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", conn);
OleDbDataAdapter da = new OleDbDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds, "myExcel");
int rows = ds.Tables[0].Rows.Count;
int cols = ds.Tables[0].Columns.Count;
string FH1;
string DM1;
for (int i = 3; i < rows; i++)
{
FH1 = ds.Tables[0].Rows[i][1].ToString().Trim();
DM1 = ds.Tables[0].Rows[i][2].ToString().Trim();
}//end for
conn.Close();
}
3.写入数据
/// 向Excel写入数据
/// </summary>
/// <param name="rows"></param>
/// <param name="cols"></param>
/// <param name="itemType"></param>
/// <param name="pageQty"></param>
/// <param name="excelTemplate">Excel模板</param>
/// <param name="excelPath">写入后的Excel保存路径</param>
public static void WriteInExcel(int rows, int cols, string itemType, string pageQty, string excelTemplate,string excelPath)
{
Application excelApp
= new Application();Workbooks excelBooks = excelApp.Workbooks;
//打开一个现有的工作薄
_Workbook excelBook = excelBooks.Add(excelTemplate);
Sheets shs = excelBook.Sheets;
//选择第一个Sheet页
_Worksheet excelSheet = (_Worksheet)shs.get_Item(1);
if (itemType == "2")
{
excelSheet.Cells[rows, cols + 2] = pageQty;
}
if (itemType == "4")
{
excelSheet.Cells[rows, cols + 3] = pageQty;
}
excelApp.AlertBeforeOverwriting = false;
excelApp.DisplayAlerts = false;
excelBook.SaveAs(excelPath,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
excelBook.Close(
//注意资源释放先后
ReleaseCOM(excelSheet);
ReleaseCOM(shs);
ReleaseCOM(excelBook);
ReleaseCOM(excelBooks);
excelApp.Quit();
ReleaseCOM(excelApp);
GC.Collect();
}
//资源释放
private static void ReleaseCOM(object pObj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(pObj);
}
catch
{
throw new Exception("Release resource Error!");
}
finally { pObj = null; }
}