Asp.net操作Excel (用Com方式)

   protected void Page_Load(object sender, EventArgs e)
        {
            
if (!Page.IsPostBack)
            {
                ApplicationClass app 
= new ApplicationClass();
                Workbook workBook 
= app.Workbooks.Open(@"e:\tt.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                Worksheet sheet 
= (Worksheet)workBook.Worksheets[1];
                Response.Write(sheet.Name + "<br/>");
                Range range 
= sheet.get_Range("E7:J112", Type.Missing);
                Range item 
= null;
                
for (int row = 0; row < range.Rows.Count; row++)
                {
                    
for (int col = 0; col < range.Columns.Count; col++)
                    {
                        item 
= (Range)range.get_Item(row, col);
                        Response.Write(item.Value2);
                        Response.Write(
" | ");
                    }
                    Response.Write(
"<br/>");
                }
                
//关闭
                app.Workbooks.Close();
                app.Quit();
                
//释放
                System.Runtime.InteropServices.Marshal.ReleaseComObject(item);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(workBook);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(app);

                item 
= null;
                app 
= null;
                workBook 
= null;
                range 
= null;

                GC.Collect();
                
//杀进程
                try{
                KillExcelProcess();
                }
catch{}
            }
        }

        
public void KillExcelProcess()
        {
            Process[] myProcesses;

            myProcesses 
= Process.GetProcessesByName("Excel");

            
foreach (Process myProcess in myProcesses)
            {
                myProcess.Kill();
            }
        }

 


posted on 2010-12-30 11:46  Maxwell Hu  阅读(525)  评论(0编辑  收藏  举报