您的位置:首页 > 编程语言 > C#

用C#替换宏,实现动态创建Excel下拉框及批注

2009-12-14 16:47 405 查看
//添加引用对应的Excel命名空间

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Excel = Microsoft.Office.Interop.Excel;
using System.Diagnostics;

namespace windows1
{
public partial class newtest : DevExpress.XtraEditors.XtraForm
{
public newtest()
{
InitializeComponent();
}

private void simpleButton1_Click(object sender, EventArgs e)
{
KillProcess("Excel");//首先杀死进程
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
Microsoft.Office.Interop.Excel.Range range = worksheet.Cells;

Excel.Range ran = range.get_Range("A5", "A5");
ran.AddComment("批注");
Excel.Range ran1 = worksheet.Columns.get_Range("H:H", Type.Missing);//或者.get_Range("D1", "D1").get_Resize(50,1);//获取一整列D,行数为50
ran1.Validation.Delete();//有无都可以
ran1.Validation.Add(Excel.XlDVType.xlValidateList, Excel.XlDVAlertStyle.xlValidAlertStop, Type.Missing, "1,2,3", Type.Missing);
//填充值
worksheet.Cells[1, 1] = "姓名";
worksheet.Cells[1, 2] = "年龄";
worksheet.Cells[1, 3] = "性别";
worksheet.Cells[2, 1] = "张三";
worksheet.Cells[2, 2] = "14";
worksheet.Cells[2, 3] = "男";
workbook.SaveCopyAs("E://tt.xls");
workbook.Saved = true;
xlApp.Visible = true;
// ran1.Validation.Modify(Excel.XlDVType.xlValidateList, Excel.XlDVAlertStyle.xlValidAlertStop, Type.Missing, "4,3,2", Type.Missing);//用此法方(Modify)可以对前面的下拉框进行修改,

}

//杀死进程
private void KillProcess(string processName)
{
//获得进程对象,以用来操作
System.Diagnostics.Process myproc = new System.Diagnostics.Process();
//得到所有打开的进程
try
{
//获得需要杀死的进程名
foreach (Process thisproc in Process.GetProcessesByName(processName))
{
//立即杀死进程
thisproc.Kill();
}
}
catch (Exception Exc)
{
throw new Exception("", Exc);
}
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐