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

所属分类: 软件编程 / C#教程 阅读数: 83
收藏 0 赞 0 分享

今天工作中遇到一个需求,就是获取 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,添加引用。

更多精彩内容其他人还在看

C#抽象类与抽象方法详解

这篇文章主要为大家详细介绍了C#抽象类与抽象方法的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

C#代码实现扑克牌排序的几种方式

今天小编就为大家分享一篇关于C#代码实现扑克牌排序,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
收藏 0 赞 0 分享

C#泛型概念的简介与泛型的使用

今天小编就为大家分享一篇关于C#泛型概念的简介与泛型的使用,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
收藏 0 赞 0 分享

C# 7.0 使用下划线忽略使用的变量的原因分析

这篇文章主要介绍了C# 7.0 使用下划线忽略使用的变量的原因浅析,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享

C# 中使用正则表达式匹配字符的含义

正则表达式的作用用来描述字符串的特征。本文重点给大家介绍C# 中使用正则表达式匹配字符的含义,非常不错,具有一定的参考借鉴价值,需要的朋友参考下吧
收藏 0 赞 0 分享

C# Dictionary和SortedDictionary的简介

今天小编就为大家分享一篇关于C# Dictionary和SortedDictionary的简介,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
收藏 0 赞 0 分享

C#中SQL Command的基本用法

今天小编就为大家分享一篇关于C#中SQL Command的基本用法,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
收藏 0 赞 0 分享

C#使用SQL DataReader访问数据的优点和实例

今天小编就为大家分享一篇关于C#使用SQL DataReader访问数据的优点和实例,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
收藏 0 赞 0 分享

C#使用SQL Dataset数据集代码实例

今天小编就为大家分享一篇关于的文章,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
收藏 0 赞 0 分享

C#使用SQL DataAdapter数据适配代码实例

今天小编就为大家分享一篇关于C#使用SQL DataAdapter数据适配代码实例,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
收藏 0 赞 0 分享
查看更多