-
publicvoidCreateExcel()
-
{
-
//创建一个Excel文件
-
Microsoft.Office.Interop.Excel.Application myExcel = newMicrosoft.Office.Interop.Excel.Application();
-
Microsoft.Office.Interop.Excel.Workbook excelWorkbook = null;
-
Microsoft.Office.Interop.Excel.Worksheet excelSheet = null;
-
myExcel.Application.Workbooks.Add(true);
-
-
//让Excel文件可见
-
myExcel.Visible = true;
-
-
myExcel.Cells[1, 4] = "普通报表";
-
-
//逐行写入数据
-
for(inti = 0; i < 11; i++)
-
{
-
for(intj = 0; j < 7; j++)
-
{
-
//以单引号开头,表示该单元格为纯文本
-
myExcel.Cells[2 + i, 1 + j] = "'"+ i;
-
}
-
}
-
-
try
-
{
-
stringexcelTemp ="c://a.xls";
-
-
//excelWorkbook = myExcel.Workbooks[1];
-
excelWorkbook = myExcel.ActiveWorkbook;
-
excelSheet = (Microsoft.Office.Interop.Excel.Worksheet)excelWorkbook.ActiveSheet;
-
-
//设定允许操作的单元格
-
Microsoft.Office.Interop.Excel.AllowEditRanges ranges = excelSheet.Protection.AllowEditRanges;
-
ranges.Add("Information",
-
myExcel.Application.get_Range("B2", "B2"),
-
Type.Missing);
-
-
//保护工作表
-
excelSheet.Protect("MyPassword", Type.Missing, Type.Missing, Type.Missing,
-
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
-
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
-
Type.Missing, true, Type.Missing, Type.Missing);
-
-
//Realease the com object
-
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelSheet);
-
excelSheet = null;
-
-
-
//Save the result to a temp path
-
excelWorkbook.SaveAs(excelTemp, Excel.XlFileFormat.xlWorkbookNormal,
-
null, null, false, false,
-
Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing,
-
Type.Missing, Type.Missing,Type.Missing,Type.Missing);
-
}
-
catch(Exception ex)
-
{
-
throw;
-
}
-
finally
-
{
-
if(excelWorkbook != null)
-
{
-
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelWorkbook);
-
excelWorkbook = null;
-
}
-
if(myExcel != null)
-
{
-
myExcel.Workbooks.Close();
-
myExcel.Quit();
-
System.Runtime.InteropServices.Marshal.ReleaseComObject(myExcel);
-
myExcel = null;
-
}
-
-
GC.Collect();
-
}
-
}
-
-
主要用Protect()方法保护工作表,Worksheet.Protection.AllowEditRanges设置允许编辑的单元格。
来自Wang_Zemin闲的蛋疼时候写的空间搬家工具
文章迁移自我的百度空间 o0o王泽民o0o