C#中对于excel2007的读,写操作

1.excel的进程的杀死.

2.excel的写操作,excel的下标是从1开始的.

3.对excel中空的操作.是DBnull不时null.
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.IO;
using Microsoft.Office.Interop.Excel;
namespace TestAccess
{
    class Program
    {
        static void Main(string[] args)
        {

            string strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;";
            strConnection += @"Data Source=C:\Documents and Settings\v-changl\My Documents\couse.xlsx;";
            strConnection += "Extended Properties=\"Excel 12.0 Xml;HDR=YES\";";
            OleDbConnection objConnection = new OleDbConnection(strConnection);
            objConnection.Open();
            OleDbDataAdapter myCommandd = new OleDbDataAdapter("select * from [Sheet1$]", objConnection);
            DataSet ds = new DataSet();
            myCommandd.Fill(ds, "[Sheet1$]");
            System.Data.DataTable dt = ds.Tables["[Sheet1$]"];
            Console.WriteLine(dt.Columns[0].ToString());
            Console.WriteLine(dt.Columns[1].ToString());
            DataRow drDisplay = dt.Rows[0];
            int[] num = new int[dt.Columns.Count];
            for (int j = 0; ; )
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {

                    if (drDisplay[i] is DBNull) ;
                    else
                        num[i] += Convert.ToInt32(drDisplay[i]);

                }
                if (++j >= dt.Rows.Count) break;
                drDisplay = dt.Rows[j];
            }
            objConnection.Close();
            object MissingValue = Type.Missing;
            Microsoft.Office.Interop.Excel.Application app = new Application();
            Microsoft.Office.Interop.Excel.Workbook wbook = app.Workbooks.Open(@"C:\Documents and Settings\v-changl\My Documents\couse.xlsx", MissingValue,
MissingValue, MissingValue, MissingValue,
MissingValue, MissingValue, MissingValue,
MissingValue, MissingValue, MissingValue,
MissingValue, MissingValue, MissingValue,
MissingValue);
            Microsoft.Office.Interop.Excel.Worksheet wsheet = wbook.ActiveSheet as Microsoft.Office.Interop.Excel.Worksheet;
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                //注意下面是i+1,,excel小标默认从1开始
                wsheet.Cells[dt.Rows.Count + 2, i + 1] = num[i].ToString();
            }

            wbook.Save();
            wbook.Close(true, null, null);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(wsheet);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(wbook);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
            wsheet = null;
            wbook = null;
            app = null;
            GC.Collect();
        }
    }
}

posted @ 2009-08-18 15:29  oraclejava  阅读(610)  评论(0)    收藏  举报