程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> .NET實例教程 >> VS2005[C#] 操作 Excel 全攻略

VS2005[C#] 操作 Excel 全攻略

編輯:.NET實例教程

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;
using System.Data.SqlClIEnt;
using System.Data.OleDb;
using System.Reflection;
namespace ExcelPrj
{
    /// <summary>
    /// Excel 系統中的主文件Excel.exe 本身就是 COM 組件,通過在.Net 項目中引用Exel.exe 文件可以實現對Excel 的功能控制
    /// 與COM 組件相互操作是通過使用"包裝類"(Wrapper Class) 和"代理"(Proxy) 的機制實現的.包裝類使.Net 程序可以識別COM 組件提供的接口,而代理類則是提供對 COM 接口的訪問
    /// </summary>
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            ExportTasks(Bind(), dataGridVIEw1);
        }
        //如果 Excel 安裝在計算機上,側導出表格內容到 Excel
        public void ExportTasks(DataSet TasksData, DataGridView TasksGridVIEw)
        {
            // 定義要使用的Excel 組件接口
            // 定義Application 對象,此對象表示整個Excel 程序
            Microsoft.Office.Interop.Excel.Application ExcelApp = null ;
            // 定義Workbook對象,此對象代表工作薄
            Microsoft.Office.Interop.Excel.Workbook workBook;
            // 定義Worksheet 對象,

此對象表示Execel 中的一張工作表
            Microsoft.Office.Interop.Excel.Worksheet ws=null;
            //定義Range對象,此對象代表單元格區域
            Microsoft.Office.Interop.Excel.Range r;

            int row = 1; int cell = 1;
            try
            {
               //初始化 Application 對象 ExcelApp
                ExcelApp = new Microsoft.Office.Interop.Excel.Application();
                //在工作薄的第一個工作表上創建任務列表
                workBook = ExcelApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);

                ws =(Worksheet)workBook.Worksheets[1];

                // 命名工作表的名稱為 "Task Management"
                ws.Name = "Task Management";

                #region 創建表格的列頭
                // 遍歷數據表中的所有列
                foreach (DataGridViewColumn cs in TasksGridVIEw.Columns)
                {
                    // 假如並不想把主鍵也顯示出來
    

                if (cs.HeaderText != "編號")
                    {
                        ws.Cells[row, cell] = cs.HeaderText;
                        r = (Range)ws.Cells[row, cell];

                        ws.get_Range(r, r).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
              
     

      //此處用來設置列的樣式
                        cell++;
                    }
                }
            
                // 創建行,把數據視圖記錄輸出到對應的Excel 單元格
                for (int i = 2; i < TasksData.Tables[0].Rows.Count; i++)
                {
                    for (int j = 1; j < TasksData.Tables[0].Columns.Count; j++)
                    {
      &nbsp;                
                        ws.Cells[i, j] = TasksData.Tables[0].Rows[i][j].ToString();
                       // r = (Range)ws.Cells[i,j];

                        Range rg = (Range)ws.get_Range(ws.Cells[i, j], ws.Cells[i, j]);
                        rg.EntireColumn.ColumnWidth = 20;
                   //     rg.Columns.AutoFit();
                        rg.NumberFormatLocal = "@";
                    }

                }
                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
           
            //顯示 Excel
            ExcelApp.Visible = true;    

     
           
        }

        private void button5_Click(object sender, EventArgs e)
        {
            DataSet ds = Bind();
            dataGridVIEw1.DataSource = ds.Tables[0];
        }
        private DataSet Bind()
        {
            SqlConnection conn = new SqlConnection("Server=.;Database=testManage;Integrated Security=SSPI");
            SqlDataAdapter da = new SqlDataAdapter("select FNumber,FExamNum,FName,FSex,FJobAdd,FCardID,FBirDate from stuInfo", conn);
            DataSet ds = new DataSet();
            da.Fill(ds);
            return ds;
        }
        private void button2_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Title = "請選擇將導出的Excel文件存放路徑";
            sfd.FileName = System.DateTime.Now.ToShortDateString() + "-學生信息";
            sfd.Filter = "Ex
cel文檔(*.xls)|*.xls";
            sfd.ShowDialog();
          
            if (sfd.FileName != "")
            {
               
                Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application();
                if (ExcelApp == null)
                {
                    MessageBox.Show("無法創建Excel對象,可能您的機器未安裝Excel");
                }
                else
                {
                    Microsoft.Office.Interop.Excel.Workbooks workbooks = ExcelApp.Workbooks;
                    Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
                    Microsoft.Office.Interop.Excel.Worksheet worksheet =(Worksheet) workbook.Worksheets[1];
                    DataSet ds=Bind();
                    for (int i = 1; i < ds.Tables[0].Rows.Count; i++)
                    {
                        for (int j = 1; j

< ds.Tables[0].Columns.Count;j++ )
                        {
                            if (i == 1)
                            {
                                worksheet.Cells[i, j] = dataGridVIEw1.Columns[j].HeaderText;
                               
                            }
                            worksheet.Cells[i+1, j] = ds.Tables[0].Rows[i][j].ToString();
                        }
                    }
                    //保存方式一:保存WorkBook
                      //workbook.SaveAs(@"F:\CData.xls",
                      // Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,
                   

; // Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,Missing.Value,Missing.Value,Missing.Value,
                      // Missing.Value,Missing.Value);

                      //保存方式二:保存WorkSheet
                      // worksheet.
SaveAs(@"F:\CData2.xls",
                      // Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                      // Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);

                     ////保存方式三
                     //workbook.Saved = true;
                     //workbook.SaveCopyAs(sfd.FileName);
               

                    System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
                    worksheet = null;
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
                    workbook = null;
  

;                  workbooks.Close();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks);
                    workbooks = null;
                    ExcelApp.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(ExcelApp);
                    ExcelApp = null;
                    MessageBox.Show("導出Excel完成!");
                }
            }

         
        }
        private void button4_Click(object sender, EventArgs e)
        {
            string strExcelFileName = @"F:\\2007-07-16-學生信息.xls";
            string strSheetName = "sheet1";

            #region ASPnet 操作Excel  正確
            ////源的定義
            //string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = " + strExcelFileName + ";Extended PropertIEs ='Excel 8.0;HDR=NO;IMEX=1'";

       &nbsp;    ////Sql語句
            //string strExcel = "select * from  [" + strSheetName + "$]";

            ////定義存放的數據表
            //DataSet ds = new DataSet();

            ////連接數據源
            //OleDbConnection conn = new OleDbConnection(strConn);

            //conn.Open();

            ////適配到數據源
            //OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, conn);
            //adapter.Fill(ds,"res");

            //conn.Close();

            //// 一般的情況下. Excel  表格的第一行是列名
            //dataGridVIEw2.DataSource = ds.Tables["res"];
            #endregion

       &nbsp;    #region COM 組件讀取復雜Excel
            Microsoft.Office.Interop.Excel.Application ExcelApp = null;
            Microsoft.Office.Interop.Excel.Workbook workBook;
            Microsoft.Office.Interop.Excel.Worksheet ws = null;

            try
            {
          

      ExcelApp = new Microsoft.Office.Interop.Excel.Application();
                workBook = ExcelApp.Workbooks.Open(@"F:\\Book1.xls", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                ws = (Worksheet)workBook.Worksheets[1];

                        
                //Excel 默認為 256 列..
                MessageBox.Show(ws.Cells.Columns.Count.ToString());
                ExcelApp.Quit();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            #endregion
        }
    }
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved