C# 解析 Excel 并且生成 Csv 文件代碼分析
今天工作中遇到一個(gè)需求,就是獲取 excel 里面的內(nèi)容,并且把 excel 另存為 csv,因?yàn)楸救艘郧拔唇佑|過(guò),所以下面整理出來(lái)的代碼均來(lái)自網(wǎng)絡(luò),具體參考鏈接已丟失,原作者保留所有權(quán)利!
例子:
using System;
using System.Data;
namespace ExportExcelToCode
{
class ExcelOperater
{
public void Operater()
{
// Excel 路徑
string excelPath = "";
// Csv 存放路徑
string csvPath = "";
// 獲取 Excel Sheet 名稱(chēng)列表
string[] sheetNameList = ExcelUtils.GetSheetNameList(excelPath);
if (sheetNameList != null && sheetNameList.Length > 0)
{
foreach (string sheetName in sheetNameList)
{
string itemName = sheetName.TrimEnd(new char[] { '$' });
// 解析 Excel 為 DataTable 對(duì)象
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 名稱(chēng)
/// </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 轉(zhuǎn) 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 轉(zhuǎn) 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();
}
}
}
}
需要特別指出的是:需要在項(xiàng)目中添加 Microsoft.Office.Interop.Excel.dll 文件,具體操作:選中引用->右鍵添加引用->瀏覽找到 Microsoft.Office.Interop.Excel,添加引用。
相關(guān)文章
Unity?數(shù)據(jù)存儲(chǔ)和讀取的方法匯總
這篇文章主要介紹了Unity?數(shù)據(jù)存儲(chǔ)和讀取的方法,本文通過(guò)四種方法在 Unity 中實(shí)現(xiàn)數(shù)據(jù)存儲(chǔ)和讀取方法的案例內(nèi)容,結(jié)合示例代碼給大家講解的非常詳細(xì),需要的朋友可以參考下2022-10-10C# 大小寫(xiě)轉(zhuǎn)換(金額)實(shí)例代碼
C# 大小寫(xiě)轉(zhuǎn)換(金額)實(shí)例代碼,需要的朋友可以參考一下2013-03-03

深入講解C#編程中嵌套類(lèi)型和匿名類(lèi)型的定義與使用

C#如何實(shí)現(xiàn)監(jiān)控手機(jī)屏幕(附源碼下載)

c# SQLHelper(for winForm)實(shí)現(xiàn)代碼

unity3D實(shí)現(xiàn)物體任意角度自旋轉(zhuǎn)