C#读写 Excel文件类

最近整理了下前段时间做的东西,关于Excel的读写,在网上也看到不少关于这方面的代码,还是觉得不是很完善,就自己整理了一个Excel文件读写的类。代码如下:

    /// <summary>
    /// 标题:Excel文件助手类
    /// 描述:1.读取指定条件的Excel信息到内存中
    ///       2.将内存中的信息导出到Excel文件中
    /// </summary>


    class Excel
    {
        //类成员
        private string m_filepath;//文件路径
        public OleDbConnection pOleDbconnection; //文件链接
        string strConnection;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="filepath">excel文件路径</param>
        public Excel (string filepath)
        {
            m_filepath = filepath;

        }
        public Excel ()
        {
        }
        /// <summary>
        /// 获取数据源
        /// </summary>
        /// <param name="filepath_">Excel文件路径</param>
        /// <returns>Excel表格数据集</returns>
        /// <example>
        /// Provider代表连接驱动4.0版本
        /// Data Source代表Excel的路径
        /// Extended Properties代表连接Excel的版本,对于Excel 97以上版本都用Excel 8.0
        /// HDR代表默认Excel第一行是否列名,Yse代表是可以直接读取,No反之1
        /// </example>

        public DataSet Excel2DataSet (string filepath_)
        {
            
                //获取文件扩展名
                string fileType = System.IO.Path.GetExtension(filepath_);
                if(fileType==".xls")
                {
                    strConnection = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + m_filepath + ";Extended Properties=Excel 8.0";    
                }
                else if(fileType == ".xlsx")
                {
                    strConnection = @"Provider=Microsoft.Jet.OLEDB.12.0;Data Source=" + m_filepath + ";Extended Properties=Excel 12.0";
                }
                else if(string.IsNullOrEmpty(fileType))
                {
                    return null;
                }
                DataSet dataSet = new DataSet();
                System.Data.DataTable dtSheetName = new System.Data.DataTable();
                OleDbDataAdapter dataAdapter;//数据适配器
                try
                {   //初始化链接并打开
                    pOleDbconnection = new OleDbConnection(strConnection);
                    pOleDbconnection.Open();
 
                    //获取数据源的表定义元数据
                    string SheetName = "";
                    dtSheetName = pOleDbconnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,new object[] {null,null,null,"TABLE" });
                   
                    //初始化适配器
                    dataAdapter = new OleDbDataAdapter();
                    for(int i = 0;i < dtSheetName.Rows.Count;i++)
                    {
                        SheetName = (string)dtSheetName.Rows[i]["TABLE_NAME"];
                        string sql_F = @"Select * FROM [" + SheetName + "]";//SQL
                        //筛选有效表
                        if(SheetName.Contains("$") || SheetName.Replace("'","").EndsWith("$"))
                        {
                            dataAdapter.SelectCommand = new OleDbCommand(sql_F,pOleDbconnection);
                            DataSet dsItem = new DataSet();
                            dataAdapter.Fill(dsItem,"[" + SheetName + "]");
                            dataSet.Tables.Add(dsItem.Tables[0].Copy());
                        }
                     
                    }

                }
                catch(Exception ex)
                {

                    System.Windows.Forms.MessageBox.Show("链接Excel出错!"+ex.Message);
                }

            return dataSet;
        }
         /// <summary>
         /// 将DataTable导出到Excel
         /// </summary>
         /// <param name="excelTable">DataTable</param>
         /// <param name="strFilepath">文件路径</param>
        public void DataTable2Excel (System.Data.DataTable excelTable,string strFilepath)
        {
            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.ApplicationClass();

            try
            {
                app.Visible = false;
                Microsoft.Office.Interop.Excel.Workbook wBook = app.Workbooks.Add(true);
                Microsoft.Office.Interop.Excel.Worksheet wSheet = wBook.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet;
                if(excelTable.Rows.Count > 0)
                {
                    int row = 0;
                    row = excelTable.Rows.Count;
                    int col = excelTable.Columns.Count;
                    for(int i = 0;i < row;i++)
                    {
                        for(int j = 0;j < col;j++)
                        {
                            string str = excelTable.Rows[i][j].ToString();
                            wSheet.Cells[i + 2,j + 1] = str;
                        }
                    }
                }

                int size = excelTable.Columns.Count;
                for(int i = 0;i < size;i++)
                {
                    wSheet.Cells[1,1 + i] = excelTable.Columns[i].ColumnName;
                }
                //设置禁止弹出保存和覆盖的询问提示框   
                app.DisplayAlerts = false;
                app.AlertBeforeOverwriting = false;
                //保存工作簿   
                wBook.Save();
                //保存excel文件   
                app.Save(strFilepath);
                app.SaveWorkspace(strFilepath);
                app.Quit();
                app = null;
              
            }
            catch(Exception err)
            {
               System.Windows.Forms.MessageBox.Show("导出Excel出错!错误原因:" + err.Message,"提示信息",
                    System.Windows.Forms.MessageBoxButtons.OK,System.Windows.Forms.MessageBoxIcon.Information);
               
            }
            finally
            {
            }  
        }
       
    }


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#读写 Excel 文件可以使用 Microsoft Office 应用程序或开源库。以下是使用 Microsoft Office 应用程序的示例代码: ```csharp using System; using System.Data; using System.Data.OleDb; class ExcelReadWrite { static void Main() { string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=example.xlsx;Extended Properties='Excel 12.0;HDR=YES;'"; // 读取数据 using (OleDbConnection connection = new OleDbConnection(connectionString)) { connection.Open(); OleDbCommand command = new OleDbCommand("SELECT * FROM [Sheet1$]", connection); OleDbDataAdapter adapter = new OleDbDataAdapter(command); DataTable dataTable = new DataTable(); adapter.Fill(dataTable); foreach (DataRow row in dataTable.Rows) { Console.WriteLine(row["Column1"].ToString() + "\t" + row["Column2"].ToString()); } } // 写入数据 using (OleDbConnection connection = new OleDbConnection(connectionString)) { connection.Open(); OleDbCommand command = new OleDbCommand("INSERT INTO [Sheet1$] ([Column1], [Column2]) VALUES (@Column1, @Column2)", connection); command.Parameters.AddWithValue("@Column1", "Value1"); command.Parameters.AddWithValue("@Column2", "Value2"); int rowsAffected = command.ExecuteNonQuery(); Console.WriteLine(rowsAffected.ToString() + " rows inserted."); } } } ``` 以上代码使用 `OleDbConnection` 和 `OleDbCommand` 连接到 Excel 文件,并读取或写入数据。需要注意的是,这种方法需要安装 Microsoft Office 应用程序才能工作,且需要保证 Excel 文件的格式正确。 开源库方面,可以使用 `EPPlus` 或 `NPOI` 库来读写 Excel 文件。以下是使用 `EPPlus` 库的示例代码: ```csharp using System; using OfficeOpenXml; class ExcelReadWrite { static void Main() { string filePath = @"example.xlsx"; // 读取数据 using (ExcelPackage package = new ExcelPackage(new System.IO.FileInfo(filePath))) { ExcelWorksheet worksheet = package.Workbook.Worksheets[1]; for (int row = 1; row <= worksheet.Dimension.Rows; row++) { Console.WriteLine(worksheet.Cells[row, 1].Value.ToString() + "\t" + worksheet.Cells[row, 2].Value.ToString()); } } // 写入数据 using (ExcelPackage package = new ExcelPackage(new System.IO.FileInfo(filePath))) { ExcelWorksheet worksheet = package.Workbook.Worksheets[1]; worksheet.Cells[worksheet.Dimension.Rows + 1, 1].Value = "Value1"; worksheet.Cells[worksheet.Dimension.Rows + 1, 2].Value = "Value2"; package.Save(); } } } ``` 以上代码使用 `ExcelPackage` 连接到 Excel 文件,并读取或写入数据。需要注意的是,这种方法需要安装 `EPPlus` 库才能工作。 综上所述,读写 Excel 文件有多种方法,可以根据具体情况选择合适的方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值