日期:2014-05-18  浏览次数:20775 次

c# winform 程序 读取Excel
是一个桌面程序,怎么实现读取Excel呢然后将内容生成一个txt文档呢?
好像要引用什么的,,,
新手,所以请大家耐心教下我。多谢!!

------解决方案--------------------
C# code
/// <summary>
        /// 上传Excel文件到服务器端
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnUpdateComment_Click(object sender, EventArgs e) {
            //第一步,上传EXCEL到服务器端
            if (FileUpload1.HasFile) {
                //验证EXCEL文件格式
                if (FileUpload1.FileName.ToLower().IndexOf(".xls") == -1) {
                    RequiredFieldValidator1.ErrorMessage = "不是有效的Excel文件";
                    RequiredFieldValidator1.IsValid = false;
                    return;
                }

                //EXCEL评论保存位置
                string _FilePath = string.Empty;
                if (System.Configuration.ConfigurationManager.AppSettings["CommentExcelFile"] != null) {
                    _FilePath = System.Configuration.ConfigurationManager.AppSettings["CommentExcelFile"].ToString();
                }

                //如果此目录不存在则创建此目录
                if (!System.IO.Directory.Exists(_FilePath)) {
                    System.IO.Directory.CreateDirectory(_FilePath);
                }

                //生成文件名称
                string _FileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "-" + DateTime.Now.Ticks.ToString().Substring(0, 4) + ".xls";
                _FileName = _FilePath + @"\" + _FileName;

                //保存此文件到服务器指定位置
                try {
                    FileUpload1.SaveAs(_FileName);
                    Response.Redirect(string.Format("CommentDetail.aspx?FileName={0}", _FileName));
                } catch (Exception exp) {
                    throw exp;
                }
            }
        }












#region 读取EXCEL
        /// <summary>
        /// 读取Excel文档
        /// </summary>
        /// <param name="Path">文件名称</param>
        /// <returns>返回一个数据集</returns>
        /// http://dev.csdn.net/article/72/72658.shtm
        public static DataSet ExcelToDS(string Path) {
            if (!string.IsNullOrEmpty(Path)) {
                string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;";
                OleDbConnection conn = new OleDbConnection(strConn);
                conn.Open();
                string strExcel = "";
                OleDbDataAdapter myCommand = null;
                DataSet ds = null;
                strExcel = "select * from [sheet1$]";
                myCommand = new OleDbDataAdapter(strExcel, strConn);
                ds = new DataSet();
                myCommand.Fill(ds);
                return ds;
            }
            return null;
        }
        #endregion




try {
                    DataSet ds = CommUtil.ExcelToDS(_FileName);
                    if (ds != null
                        && ds.Tables.Count > 0
                        && ds.Tables[0].Rows.Count > 0) {

//略...