读书人

C# 读2007Excel资料

发布时间: 2012-06-27 14:20:09 作者: rapoo

C# 读2007Excel文件

今天遇到一个问题:

C#去读Excel文件

?

这里提供源代码

为了怕自己忘记,这里记录一下

?

?

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Collections;using System.IO;using System.Reflection;using MSExcel = Microsoft.Office.Interop.Excel;namespace ExcelTool{    public partial class FrmMain : Form    {        string str = @"C:\Program Files\Data\SpaceKeyword.xlsx";        object missing = Missing.Value;        MSExcel.Application app = null;        MSExcel.Workbook wb = null;        MSExcel.Worksheet ws = null;        MSExcel.Range r = null;        /// <summary>        /// 加载Excel        /// </summary>        private void InitExcel()        {             //打开excel            app = new Microsoft.Office.Interop.Excel.Application();            wb = app.Workbooks.Open(str, false, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);            app.Visible = false;//读Excel不显示出来影响用户体验            //得到WorkSheet对象            ws = (MSExcel.Worksheet)wb.Worksheets.get_Item(1);        }        /// <summary>        /// 读取Excel中的内容        /// </summary>        private void ReadExcel()        {            InitExcel();            //读取A1单元格内容            r = ws.get_Range("A1", Type.Missing);            string strA1 = r.Value;            app.Quit();//退出            MessageBox.Show(strA1);        }        /// <summary>        /// 写入Excel(Win7下要以管理员身份运行才能修改)        /// </summary>        private void WriteExcel()        {            InitExcel();            ws.Cells[1, 1] = "修改的内容";            //保存Excel            wb.Save();            wb.Close(null, null, null);            app.Workbooks.Close();            app.Application.Quit();            app.Quit();            System.Runtime.InteropServices.Marshal.ReleaseComObject(ws);            System.Runtime.InteropServices.Marshal.ReleaseComObject(wb);            System.Runtime.InteropServices.Marshal.ReleaseComObject(app);            ws = null;            wb = null;            app = null;        }    }}
?

?

?

?

 public class Excel    {        public static String[] getWorksheetList(String connectionString)        {            OleDbConnection objConn = null;            DataTable sheets = null;            try            {                objConn = new OleDbConnection(connectionString);                objConn.Open();                sheets = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);                int k = 0;                String[] worksheets = new String[sheets.Rows.Count];                foreach (DataRow row in sheets.Rows)                {                    worksheets[k] = row["TABLE_NAME"].ToString().Replace("'", "").Replace("$", "");                }                return worksheets;            }            catch (Exception ex)            {                Console.WriteLine(ex.Message);                return null;            }            finally            {                if (objConn != null)                {                    objConn.Close();                    objConn.Dispose();                }                if (sheets != null)                    sheets.Dispose();            }        }        public static void echoAsCSV(string connectionString)        {            try            {                var adapter1 = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", connectionString);                var ds = new DataSet();                adapter1.Fill(ds, "results");                DataTable data = ds.Tables["results"];                for (int i = 0; i < data.Rows.Count; i++)                {                    for (int j = 0; j < data.Columns.Count; j++)                        Console.Write("\"" + data.Rows[i].ItemArray[j] + "\";");                    Console.WriteLine();                }            }            catch (Exception ex)            {                Console.WriteLine(ex.Message);            }        }        static void Main(string[] args)        {            foreach (String arg in args)            {                Console.WriteLine(arg);            }            var connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0;", "E:/1.xlsx");            String[] worksheetList = getWorksheetList(connectionString);            if (worksheetList != null)                foreach (String worksheetName in worksheetList)                    Console.WriteLine(worksheetName);            echoAsCSV(connectionString);            Console.Read();        }    }

读书人网 >C#

热点推荐