C# 解析 Excel 并且生成 Csv 文件代码分析

 更新时间:2014年10月20日 09:03:03   作者:omuying  
这篇文章主要介绍了C# 解析 Excel 并且生成 Csv 文件的方法和代码分享,有需要的朋友可以参考下
(福利推荐:【腾讯云】服务器最新限时优惠活动,云服务器1核2G仅99元/年、2核4G仅768元/3年,立即抢购>>>:9i0i.cn/qcloud

(福利推荐:你还在原价购买阿里云服务器?现在阿里云0.8折限时抢购活动来啦!4核8G企业云服务器仅2998元/3年,立即抢购>>>:9i0i.cn/aliyun

今天工作中遇到一个需求,就是获取 excel 里面的内容,并且把 excel 另存为 csv,因为本人以前未接触过,所以下面整理出来的代码均来自网络,具体参考链接已丢失,原作者保留所有权利!

例子:

复制代码 代码如下:

using System;
using System.Data;

namespace ExportExcelToCode
{
    class ExcelOperater
    {
        public void Operater()
        {
            // Excel 路径
            string excelPath = "";
            // Csv 存放路径
            string csvPath = "";

            // 获取 Excel Sheet 名称列表
            string[] sheetNameList = ExcelUtils.GetSheetNameList(excelPath);

            if (sheetNameList != null && sheetNameList.Length > 0)
            {
                foreach (string sheetName in sheetNameList)
                {
                    string itemName = sheetName.TrimEnd(new char[] { '$' });

                    // 解析 Excel 为 DataTable 对象
                    DataTable dataTable = ExcelUtils.ExcelToDataTable(excelPath, itemName);
                    if (dataTable != null && dataTable.Rows.Count > 0)
                    {
                        // 生成 Csv 文件
                        ExcelUtils.ExcelToCsv(excelPath, csvPath, itemName, "|#|", 0);
                    }
                }
            }
        }
    }
}

ExcelUtils.cs 文件

复制代码 代码如下:

using System;  
using System.Data;
using Microsoft.Office.Interop.Excel;
using Excel = Microsoft.Office.Interop.Excel;

namespace ExportExcelToCode
{
    public partial class ExcelUtils
    {
        /// <summary>
        /// 获取 Sheet 名称
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static string[] GetSheetNameList(string filePath)
        {
            try
            {
                string connectionText = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + filePath + ";" + "Extended Properties='Excel 12.0;HDR=YES;IMEX=1';";

                System.Data.OleDb.OleDbConnection oleDbConnection = new System.Data.OleDb.OleDbConnection(connectionText);

                oleDbConnection.Open();

                System.Data.DataTable dataTable = oleDbConnection.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" }); ;

                string[] sheetNameList = new string[dataTable.Rows.Count];

                for (int index = 0; index < dataTable.Rows.Count; index++)
                {
                    sheetNameList[index] = dataTable.Rows[index][2].ToString();
                }

                oleDbConnection.Close();

                return sheetNameList;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        /// <summary>
        /// Excel 转 DataTable
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="sheetName"></param>
        /// <returns></returns>
        public static System.Data.DataTable ExcelToDataTable(string filePath, string sheetName)
        {
            try
            {
                string connectionText = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + filePath + ";" + "Extended Properties='Excel 12.0;HDR=YES;IMEX=1';";
                string selectText = string.Format("select * from [{0}$]", sheetName);

                DataSet dataSet = new DataSet();

                System.Data.OleDb.OleDbConnection oleDbConnection = new System.Data.OleDb.OleDbConnection(connectionText);

                oleDbConnection.Open();

                System.Data.OleDb.OleDbDataAdapter oleDbDataAdapter = new System.Data.OleDb.OleDbDataAdapter(selectText, connectionText);
                oleDbDataAdapter.Fill(dataSet, sheetName);

                oleDbConnection.Close();

                return dataSet.Tables[sheetName];
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        /// <summary>
        /// Excel 转 Csv
        /// </summary>
        /// <param name="sourceExcelPathAndName"></param>
        /// <param name="targetCSVPathAndName"></param>
        /// <param name="excelSheetName"></param>
        /// <param name="columnDelimeter"></param>
        /// <param name="headerRowsToSkip"></param>
        /// <returns></returns>
        public static bool ExcelToCsv(string sourceExcelPathAndName, string targetCSVPathAndName, string excelSheetName, string columnDelimeter, int headerRowsToSkip)
        {
            Excel.Application oXL = null;
            Excel.Workbooks workbooks = null;
            Workbook mWorkBook = null;
            Sheets mWorkSheets = null;
            Worksheet mWSheet = null;

            try
            {
                oXL = new Excel.Application();
                oXL.Visible = false;
                oXL.DisplayAlerts = false;
                workbooks = oXL.Workbooks;
                mWorkBook = workbooks.Open(sourceExcelPathAndName, 0, false, 5, "", "", false, XlPlatform.xlWindows, "", true, false, 0, true, false, false);
                mWorkSheets = mWorkBook.Worksheets;
                mWSheet = (Worksheet)mWorkSheets.get_Item(excelSheetName);
                Excel.Range range = mWSheet.UsedRange;
                Excel.Range rngCurrentRow;
                for (int i = 0; i < headerRowsToSkip; i++)
                {
                    rngCurrentRow = range.get_Range("A1", Type.Missing).EntireRow;
                    rngCurrentRow.Delete(XlDeleteShiftDirection.xlShiftUp);
                }
                range.Replace("\n", " ", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                range.Replace(",", columnDelimeter, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

                mWorkBook.SaveAs(targetCSVPathAndName, Excel.XlFileFormat.xlCSV,
                Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
                Type.Missing, Type.Missing, Type.Missing,
                Type.Missing, false);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
            finally
            {
                if (mWSheet != null) mWSheet = null;
                if (mWorkBook != null) mWorkBook.Close(Type.Missing, Type.Missing, Type.Missing);
                if (mWorkBook != null) mWorkBook = null;
                if (oXL != null) oXL.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oXL);
                if (oXL != null) oXL = null;
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
            }
        }
    }
}


需要特别指出的是:需要在项目中添加 Microsoft.Office.Interop.Excel.dll 文件,具体操作:选中引用->右键添加引用->浏览找到 Microsoft.Office.Interop.Excel,添加引用。

相关文章

  • Unity?数据存储和读取的方法汇总

    Unity?数据存储和读取的方法汇总

    这篇文章主要介绍了Unity?数据存储和读取的方法,本文通过四种方法在 Unity 中实现数据存储和读取方法的案例内容,结合示例代码给大家讲解的非常详细,需要的朋友可以参考下
    2022-10-10
  • C#使用Task实现异步方法

    C#使用Task实现异步方法

    本文主要介绍了C#使用Task实现异步方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-04-04
  • C# 大小写转换(金额)实例代码

    C# 大小写转换(金额)实例代码

    C# 大小写转换(金额)实例代码,需要的朋友可以参考一下
    2013-03-03
  • C#实现简单的井字游戏实例

    C#实现简单的井字游戏实例

    这篇文章主要介绍了C#实现简单的井字游戏,以一个完整实例分析了C#实现井字游戏的方法,需要的朋友可以参考下
    2015-06-06
  • 深入讲解C#编程中嵌套类型和匿名类型的定义与使用

    深入讲解C#编程中嵌套类型和匿名类型的定义与使用

    这篇文章主要介绍了C#编程中嵌套类型和匿名类型的定义与使用,包括在SQL语句中使用匿名类型的方法,需要的朋友可以参考下
    2016-01-01
  • c# Async streams的使用解析

    c# Async streams的使用解析

    这篇文章主要介绍了c# Async streams的使用解析,帮助大家更好的理解和学习使用c#,感兴趣的朋友可以了解下
    2021-04-04
  • C#中RSA加密与解密的实例详解

    C#中RSA加密与解密的实例详解

    这篇文章主要介绍了C#中RSA加密与解密的实例代码,代码简单易懂,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-08-08
  • C#如何实现监控手机屏幕(附源码下载)

    C#如何实现监控手机屏幕(附源码下载)

    这篇文章主要介绍了C#如何实现监控手机屏幕(附源码下载),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-10-10
  • c# SQLHelper(for winForm)实现代码

    c# SQLHelper(for winForm)实现代码

    数据连接池c# SQLHelper 实现代码
    2009-02-02
  • unity3D实现物体任意角度自旋转

    unity3D实现物体任意角度自旋转

    这篇文章主要为大家详细介绍了unity3D实现物体任意角度自旋转,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-07-07

最新评论

?


http://www.vxiaotou.com