C# 操作Excel2003
前言
公司最近有操作excel的需求:店名上传上来的excel都没有地址这一栏,但是有对应的编号,由于有上百个excel文件各个分店要是手工填写的话基本不可能,所以有劳我想办法了:)我倒是知道能操作,但是没有具体实践过.以下是摸索的点滴:
开发环境
window XP,Microsoft Visual Studio 2005,C#,ASP.NET,Office2003,SQL SERVER2000
推荐/参考文章
1.强烈推荐Excel VBA文档,如果你安装了office2003的话,安装目录下有个叫VBAXL10.CHM的帮助文档就是了,并且是中文的!!例如,我安装的在D盘,那么这个文件的地址是:D:\Program Files\Microsoft Office\OFFICE11\2052\VBAXL10.CHM
2.主要参考C#向Excel报表中插入图片的2种方法,将Excel应用于报表开发系列文章共8篇等文章.
目的,步骤
1.通过程序打开excel
2.读取编号列
3.根据编号在数据库中查询对应的地址并返回数据
4.把对应的地址插入excel
5.通过程序保存关闭excel,下一个...
正题
1.(新建工程等步骤在这里都省略了)添加操作excel的COM组件:
2.主要的方法代码:
/// <summary>
/// 修改Excel
/// </summary>
/// <param name="Path">读取路径</param>
/// <param name="newPath">另存路径</param>
/// <param name="shop_name">店名</param>
/// <param name="tablename">表名</param>
public void AlterExcel(string Path,string newPath,string shop_name,string tablename)
{
try
{
Object miss = System.Reflection.Missing.Value;
Excel.Application ExcelApp = new Excel.ApplicationClass();
Excel.Workbooks wbooks = (Excel.Workbooks)ExcelApp.Workbooks;
Excel.Workbook wbook = wbooks.Open(Path, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss);
//获得第一个工作薄
Excel.Worksheet wsheet = (Excel.Worksheet)wbook.Worksheets.get_Item(1);
ExcelApp.Visible = false;
ExcelApp.DisplayAlerts = false;
//取得编号
ArrayList arr = new ArrayList();
for (int i = 3, j = wsheet.UsedRange.Rows.Count; i < j; i++)
{
Excel.Range rang = (Excel.Range)wsheet.Cells[i, 2];
if (null != rang.Text && rang.Text.ToString().Length > 0)
arr.Add(rang.Text);
else
break;
}
//添加新行 Cells[行,列]
((Excel.Range)wsheet.Columns.get_Item(3, miss)).Insert(XlInsertShiftDirection.xlShiftToRight, miss);
//添加区域单元格
//wsheet.get_Range(wsheet.Cells[2, 3], wsheet.Cells[wsheet.UsedRange.Rows.Count - 3, 3]).Insert(XlInsertShiftDirection.xlShiftToRight, miss);
//设置标头
wsheet.Cells[2, 3] = "地址";
((Excel.Range)wsheet.Columns.get_Item(3, miss)).ColumnWidth = 25;
//此处为获得该店的所有地址,这里替换成自己的方法就行
Hashtable hash = GetShopAddr(shop_name, tablename);
for (int i = 3, j = i + arr.Count; i < j; i++)
{
try
{
//根据编号设置地址
wsheet.Cells[i, 3] = hash[Convert.ToInt32(arr[i - 3])];
}
catch(Exception)
{
continue;
}
}
//另存为
wbook.SaveAs(newPath, miss, miss, miss, miss, miss, Excel.XlSaveAsAccessMode.xlNoChange, miss, miss, miss, miss, miss);
wbook.Close(false, miss, miss);
ExcelApp.Quit();
ReleaseObject(wsheet);
ReleaseObject(wbook);
ReleaseObject(wbooks);
ReleaseObject(ExcelApp);
GC.Collect();
GC.WaitForPendingFinalizers();
}
catch
{
//throw;
}
finally
{
//结束进程
//KillExcelProcess();
}
}
/// <summary>
/// 释放对象
/// </summary>
/// <param name="obj"></param>
private void ReleaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
}
catch {}
finally { obj = null; }
}
/// <summary>
/// 结束Excel进程
/// </summary>
public void KillExcelProcess()
{
Process[] myProcesses = Process.GetProcessesByName("Excel");
foreach (Process myProcess in myProcesses)
myProcess.Kill();
}
注意:/// 修改Excel
/// </summary>
/// <param name="Path">读取路径</param>
/// <param name="newPath">另存路径</param>
/// <param name="shop_name">店名</param>
/// <param name="tablename">表名</param>
public void AlterExcel(string Path,string newPath,string shop_name,string tablename)
{
try
{
Object miss = System.Reflection.Missing.Value;
Excel.Application ExcelApp = new Excel.ApplicationClass();
Excel.Workbooks wbooks = (Excel.Workbooks)ExcelApp.Workbooks;
Excel.Workbook wbook = wbooks.Open(Path, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss);
//获得第一个工作薄
Excel.Worksheet wsheet = (Excel.Worksheet)wbook.Worksheets.get_Item(1);
ExcelApp.Visible = false;
ExcelApp.DisplayAlerts = false;
//取得编号
ArrayList arr = new ArrayList();
for (int i = 3, j = wsheet.UsedRange.Rows.Count; i < j; i++)
{
Excel.Range rang = (Excel.Range)wsheet.Cells[i, 2];
if (null != rang.Text && rang.Text.ToString().Length > 0)
arr.Add(rang.Text);
else
break;
}
//添加新行 Cells[行,列]
((Excel.Range)wsheet.Columns.get_Item(3, miss)).Insert(XlInsertShiftDirection.xlShiftToRight, miss);
//添加区域单元格
//wsheet.get_Range(wsheet.Cells[2, 3], wsheet.Cells[wsheet.UsedRange.Rows.Count - 3, 3]).Insert(XlInsertShiftDirection.xlShiftToRight, miss);
//设置标头
wsheet.Cells[2, 3] = "地址";
((Excel.Range)wsheet.Columns.get_Item(3, miss)).ColumnWidth = 25;
//此处为获得该店的所有地址,这里替换成自己的方法就行
Hashtable hash = GetShopAddr(shop_name, tablename);
for (int i = 3, j = i + arr.Count; i < j; i++)
{
try
{
//根据编号设置地址
wsheet.Cells[i, 3] = hash[Convert.ToInt32(arr[i - 3])];
}
catch(Exception)
{
continue;
}
}
//另存为
wbook.SaveAs(newPath, miss, miss, miss, miss, miss, Excel.XlSaveAsAccessMode.xlNoChange, miss, miss, miss, miss, miss);
wbook.Close(false, miss, miss);
ExcelApp.Quit();
ReleaseObject(wsheet);
ReleaseObject(wbook);
ReleaseObject(wbooks);
ReleaseObject(ExcelApp);
GC.Collect();
GC.WaitForPendingFinalizers();
}
catch
{
//throw;
}
finally
{
//结束进程
//KillExcelProcess();
}
}
/// <summary>
/// 释放对象
/// </summary>
/// <param name="obj"></param>
private void ReleaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
}
catch {}
finally { obj = null; }
}
/// <summary>
/// 结束Excel进程
/// </summary>
public void KillExcelProcess()
{
Process[] myProcesses = Process.GetProcessesByName("Excel");
foreach (Process myProcess in myProcesses)
myProcess.Kill();
}
a).需要添加命名空间using Microsoft.Office.Interop.Excel;
b).添加新行处代码两个都行,一个是添加一列一个是添加一个范围的单元格,达到效果是一样的
最后推荐一个网站和一个论坛:
Excel终极伴侣 http://www.chinaobs.com/
MSDN http://msdn.microsoft.com/library/CHS/dv_wrcore/html/wrgrfexcelobjects.asp