时间:2021-05-20
今天工作中遇到一个需求,就是获取 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,添加引用。
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
前言csv文件其实和excel文件一样,都是表格类型.但PHP生成csv要比生成excel文件要简单的多,生成csv文件其实就是把以,号为分割符的字符串存成.c
本文实例讲述了C#操作CSV文件类。分享给大家供大家参考。具体分析如下:这个C#类用于转换DataTable为CSV文件、CSV文件转换成DataTable,如
本文实例为大家分享了java导出生成csv文件的具体代码,供大家参考,具体内容如下首先我们需要对csv文件有基础的认识,csv文件类似excel,可以使用exc
本文实例讲述了C#使用oledb操作excel文件的方法。分享给大家供大家参考。具体分析如下:不管什么编程语言都会提供操作Excel文件的方式,C#操作Exce
这里的方法是利用fputcsv写CSV文件的方法,直接向浏览器输出Excel文件。复制代码代码如下://输出Excel文件头,可把user.csv换成你要的文件