国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

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

2019-10-29 21:42:33
字體:
來源:轉載
供稿:網友
這篇文章主要介紹了C# 解析 Excel 并且生成 Csv 文件的方法和代碼分享,有需要的朋友可以參考下
 

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 都兰县| 汉川市| 佛教| 敦煌市| 镇江市| 三门县| 抚顺县| 静乐县| 渭源县| 高阳县| 顺昌县| 祁阳县| 普格县| 江达县| 台北市| 阿合奇县| 明溪县| 昂仁县| 雷山县| 若羌县| 德保县| 桦南县| 冀州市| 辰溪县| 海南省| 香河县| 乌兰察布市| 青阳县| 囊谦县| 林州市| 淮安市| 龙门县| 临泽县| 清涧县| 富锦市| 涟源市| 南澳县| 峨边| 鄂托克旗| 冷水江市| 双桥区|