C#下Excel文件的读取

具体的源码如下,显示打开文件浏览器选择Excel文件,对文件进行读取,最后展示出读取的部分内容。

 public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            
        }


        //添加两个函数,一个是读取Excel文件的函数,另一个是写数据进入Excel文件的函数。

        public static DataTable LoadDataFromExcel(string filePath,string sheetName)
        {
            DataSet getdata = new DataSet();
            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";
            string strExcel = string.Format("select * from [{0}$]",sheetName);

            //连接数据源
            OleDbConnection conn = new OleDbConnection(strConn);
            conn.Open();

            //适配到数据源
            OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, strConn);
            adapter.Fill(getdata, sheetName);

            conn.Close();
            return getdata.Tables[sheetName];
        }

        public static void WriteDataToExcel(DataSet DS, string filePath)
        {

        }

        //打开文件浏览器,选择需要的文件
        private void btnOpen_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Multiselect = false;
            fileDialog.Title = "请选择文件";
            fileDialog.Filter = "Excel file|*.xlsx";
            if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string file = fileDialog.FileName;
                //System.Windows.Forms.MessageBox.Show("已选择的文件:" + file);
                Pathtxt.Text = file;
            }
        }

        private void btnTransfer_Click(object sender, RoutedEventArgs e)
        {
            DataTable FurTable = LoadDataFromExcel(Pathtxt.Text, "Nov FUR");
            DataRow dtRow = FurTable.Rows[0];
            object[] RowItem = dtRow.ItemArray;
            Pathtxt.Text = "";
            foreach (object item in RowItem)
            {
                if (item.ToString() != null)
                {
                    Pathtxt.Text += item.ToString();
                    Pathtxt.Text += "  ";
                }
            }

            //System.Windows.Forms.MessageBox.Show(dtRow[0].ToString());
        }
    }

C#下Excel文件的读取

上一篇:Win7/Vista/Server2008下VS 环境 调试调用 HTTP.SYS 无法启动监听服务及启动后其他机器无法访问端口


下一篇:Windows-002-桌面无显解决方法