原文链接:http://download.csdn.net/download/x449723457/2800574
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
try
{
string ModeFile = @"" + getzm() + "" + "\\" + textBox1.Text + ".xls";
Excel.Application MyExcel = new Excel.Application();
MyExcel.Visible = false;
Excel.Workbook book = MyExcel.Application.Workbooks.Add(true);
Excel.Worksheet thisWorksheet1;
thisWorksheet1 = (Excel.Worksheet)book.Worksheets.Add(Type.Missing, Type.Missing, 1, Type.Missing);
thisWorksheet1.Name = "test";
//可以修改成 A3,B5,C8等
Excel.Range range = thisWorksheet1.get_Range("B2", "B250");
range.Validation.Add(Excel.XlDVType.xlValidateList, Excel.XlDVAlertStyle.xlValidAlertStop, Type.Missing, "a,b,c,d,f,g,h", Type.Missing);
MyExcel.ActiveWorkbook.SaveAs(ModeFile, Excel.XlFileFormat.xlWorkbookNormal, null, null, false, false, Excel.XlSaveAsAccessMode.xlNoChange, null, null, null, null, null);
book.Close(null, null, null);
MyExcel.Workbooks.Close();
MyExcel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(book);
System.Runtime.InteropServices.Marshal.ReleaseComObject(thisWorksheet1);
System.Runtime.InteropServices.Marshal.ReleaseComObject(MyExcel);
MessageBox.Show("已生成到桌面!", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
System.Diagnostics.Process.Start("explorer.exe", "/select, " +ModeFile);
}
catch
{
}
}
}
public string getzm()
{
string dir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
return dir;
}
}
效果图: