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

首頁 > 編程 > C# > 正文

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

2020-01-24 02:21:06
字體:
來源:轉載
供稿:網友

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 信宜市| 余江县| 紫金县| 南通市| 沅江市| 广元市| 台江县| 屏山县| 定襄县| 兴义市| 舒兰市| 辽阳市| 昆山市| 桃园市| 桂林市| 天台县| 昭通市| 崇明县| 绥滨县| 乌审旗| 扎囊县| 和林格尔县| 新巴尔虎右旗| 吐鲁番市| 临邑县| 班玛县| 正蓝旗| 芦溪县| 武穴市| 防城港市| 射阳县| 平陆县| 通化县| 当雄县| 永安市| 红原县| 庆阳市| 科技| 磐安县| 四会市| 东源县|