C# Execel 패키지 클래스 만들기

2800 단어 C#Excel
<span style="font-size:18px;">    /// <summary>
    /// ConnectExcel  。
    /// </summary>
    class ConnectExcel
    {
        Microsoft.Office.Interop.Excel.Application myExcel;
        Microsoft.Office.Interop.Excel.Workbook myWorkBook;
        Microsoft.Office.Interop.Excel.Worksheet mySheet;
        /// <summary>
        ///  , Excel 
        /// </summary>
        public ConnectExcel()
        {
            myExcel = new Microsoft.Office.Interop.Excel.Application();
            myWorkBook = myExcel.Application.Workbooks.Add(true);
            string filePath = Directory.GetCurrentDirectory() + @"\score.xls";
            myWorkBook = myExcel.Workbooks.Add(filePath);


            mySheet = (Microsoft.Office.Interop.Excel.Worksheet)myExcel.Worksheets[1];
            mySheet.Activate();
            myExcel.Visible = false;
        }
        /// <summary>
        ///  Excel
        /// </summary>
        /// <param name="data"> </param>
        /// <param name="starRow"> </param>
        /// <param name="startColumn"> </param>
        public bool WriteData(string data, int row, int column)
        {
            bool result = true; ;
            try
            {
                myExcel.Cells[row, column] = data;
            }
            catch
            {
                result = false;
            }
            return result;
        }
        /// <summary>
        /// Excel 
        /// </summary>
        /// <param name="fileName"> </param>
        /// <returns> True</returns>
        public bool SaveAs(string fileName)
        {
            try
            {
                myWorkBook.SaveAs(fileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        /// <summary>
        ///  Excel
        /// </summary>
        /// <param name="isSave"> </param>
        public void Close(bool isSave)
        {
            try
            {
                myWorkBook.Close(isSave, Type.Missing, Type.Missing);
                myExcel.Quit();
                myWorkBook = null;
                myExcel = null;
                //   Excel   
                System.Runtime.InteropServices.Marshal.ReleaseComObject(myExcel);
                GC.Collect();
            }
            catch
            {
            }
        }
    }</span>

좋은 웹페이지 즐겨찾기