You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
435 lines
18 KiB
435 lines
18 KiB
using System;
|
|
using System.Collections.Generic;
|
|
using System.Data;
|
|
using System.Data.OleDb;
|
|
using System.Diagnostics;
|
|
using System.Windows.Forms;
|
|
|
|
namespace CK.SCP.Utils
|
|
{
|
|
public class ExcelReader
|
|
|
|
{
|
|
|
|
private DataSet _dsExcel;
|
|
private DataTable _dtExcel;
|
|
private string _fileExt;
|
|
private string _filePath;
|
|
private List<string> _readSheetName;
|
|
// private string _saveFileName;
|
|
private string _sheetName;
|
|
private List<string> _sheetNames;
|
|
|
|
/// <summary>
|
|
/// 读取Excel文件到DataSet
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
public DataSet ReturnDataSet()
|
|
{
|
|
var openFileDialog = new OpenFileDialog { Filter = "Execl files (*.xls,*.xlsx)|*.xls;*.xlsx" };
|
|
//openFileDialog.RestoreDirectory = true;
|
|
//openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
|
|
|
|
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
|
{
|
|
_filePath = openFileDialog.FileName;
|
|
_fileExt = openFileDialog.FileName.Substring(openFileDialog.FileName.LastIndexOf('.'));
|
|
var poDv = new ProcessOperator { BackgroundWork = ReadExcelToDataSet };
|
|
poDv.BackgroundWorkerCompleted += ReadExcel_Completed;
|
|
poDv.Start();
|
|
}
|
|
return _dsExcel;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 读取Excel文件到DataSet
|
|
/// </summary>
|
|
/// <param name="filePath">Excel文件地址</param>
|
|
/// <returns></returns>
|
|
public DataSet ReturnDataSet(string filePath)
|
|
{
|
|
try
|
|
{
|
|
if (string.IsNullOrEmpty(filePath))
|
|
return ReturnDataSet();
|
|
_filePath = filePath;
|
|
_fileExt = filePath.Substring(filePath.LastIndexOf('.'));
|
|
|
|
if (_fileExt.ToUpper() == ".XLSX" || _fileExt.ToUpper() == ".XLS")
|
|
{
|
|
var poDv = new ProcessOperator { BackgroundWork = ReadExcelToDataSet };
|
|
poDv.BackgroundWorkerCompleted += ReadExcel_Completed;
|
|
poDv.Start();
|
|
}
|
|
else
|
|
{
|
|
MessageBox.Show("无法解析该后缀名的文件!");
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
MessageBox.Show(ex.Message);
|
|
}
|
|
return _dsExcel;
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
/// 读取Excel文件到DataSet
|
|
/// </summary>
|
|
/// <param name="sheetNames">读取Excel文件工作表名称集合</param>
|
|
/// <returns></returns>
|
|
public DataSet ReturnDataSet(List<string> sheetNames)
|
|
{
|
|
var openFileDialog = new OpenFileDialog { Filter = "Execl files (*.xls,*.xlsx)|*.xls;*.xlsx" };
|
|
//openFileDialog.RestoreDirectory = true;
|
|
//openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
|
|
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
|
{
|
|
_sheetNames = sheetNames;
|
|
_filePath = openFileDialog.FileName;
|
|
_fileExt = openFileDialog.FileName.Substring(openFileDialog.FileName.LastIndexOf('.'));
|
|
var poDv = new ProcessOperator { BackgroundWork = ReadExcelToDataSet };
|
|
poDv.BackgroundWorkerCompleted += ReadExcel_Completed;
|
|
poDv.Start();
|
|
}
|
|
return _dsExcel;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 读取Excel文件到DataSet
|
|
/// </summary>
|
|
/// <param name="filePath">Excel文件地址</param>
|
|
/// <param name="sheetNames">读取Excel文件表名称集合</param>
|
|
/// <returns></returns>
|
|
public DataSet ReturnDataSet(string filePath, List<string> sheetNames)
|
|
{
|
|
try
|
|
{
|
|
if (string.IsNullOrEmpty(filePath))
|
|
return ReturnDataSet();
|
|
if (sheetNames == null || sheetNames.Count == 0)
|
|
return ReturnDataSet(filePath);
|
|
|
|
_filePath = filePath;
|
|
_fileExt = filePath.Substring(filePath.LastIndexOf('.'));
|
|
_sheetNames = sheetNames;
|
|
if (_fileExt.ToUpper() == ".XLSX" || _fileExt.ToUpper() == ".XLS")
|
|
{
|
|
var poDv = new ProcessOperator { BackgroundWork = ReadExcelToDataSet };
|
|
poDv.BackgroundWorkerCompleted += ReadExcel_Completed;
|
|
poDv.Start();
|
|
}
|
|
else
|
|
{
|
|
MessageBox.Show("无法解析该后缀名的文件!");
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
MessageBox.Show(ex.Message);
|
|
}
|
|
return _dsExcel;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 读取Excel文件的sheet到DataTable
|
|
/// </summary>
|
|
/// <param name="sheetName">Excel文件表名称</param>
|
|
/// <returns></returns>
|
|
public DataTable ReturnDataTable(string sheetName)
|
|
{
|
|
var openFileDialog = new OpenFileDialog { Filter = "Execl files (*.xls,*.xlsx)|*.xls;*.xlsx" };
|
|
//openFileDialog.RestoreDirectory = true;
|
|
//openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
|
|
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
|
{
|
|
_filePath = openFileDialog.FileName;
|
|
_fileExt = openFileDialog.FileName.Substring(openFileDialog.FileName.LastIndexOf('.'));
|
|
_sheetName = sheetName;
|
|
var poDv = new ProcessOperator { BackgroundWork = ReadToDataTable };
|
|
poDv.BackgroundWorkerCompleted += ReadExcel_Completed;
|
|
poDv.Start();
|
|
}
|
|
return _dtExcel;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 读取Excel文件的sheet到DataTable
|
|
/// </summary>
|
|
/// <param name="filePath">Excel文件地址</param>
|
|
/// <param name="sheetName">Excel文件表名称</param>
|
|
/// <returns></returns>
|
|
public DataTable ReturnDataTable(string filePath, string sheetName)
|
|
{
|
|
try
|
|
{
|
|
if (string.IsNullOrEmpty(filePath))
|
|
return ReturnDataTable(sheetName);
|
|
_filePath = filePath;
|
|
_fileExt = filePath.Substring(filePath.LastIndexOf('.'));
|
|
|
|
if (_fileExt.ToUpper() == ".XLSX" || _fileExt.ToUpper() == ".XLS")
|
|
{
|
|
_sheetName = sheetName;
|
|
var poDv = new ProcessOperator { BackgroundWork = ReadToDataTable };
|
|
poDv.BackgroundWorkerCompleted += ReadExcel_Completed;
|
|
poDv.Start();
|
|
}
|
|
else
|
|
{
|
|
MessageBox.Show("无法解析该后缀名的文件!");
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
MessageBox.Show(ex.Message);
|
|
}
|
|
return _dtExcel;
|
|
}
|
|
|
|
private void ReadExcel_Completed(object sender, BackgroundWorkerEventArgs e)
|
|
{
|
|
if (e.BackGroundException == null)
|
|
{
|
|
//if (readSheetName != null && readSheetName.Count > 0)
|
|
//{
|
|
// //StringBuilder sb = new StringBuilder();
|
|
// //sb.Append("文件读取成功!\n\r已在" + filePath + "下\n\r读取了 " + readSheetName.Count.ToString() + " 张Sheet工作表\n\r分别是:\n\r");
|
|
// //int i = 0;
|
|
// //foreach (String SheetName in readSheetName)
|
|
// //{
|
|
// // i ++;
|
|
// // sb.Append(SheetName + ",");
|
|
// // if (i % 3 == 0)
|
|
// // {
|
|
// // sb.Append("\n\r");
|
|
// // }
|
|
// //}
|
|
// //String message = sb.ToString();
|
|
// //message = message.Substring(0, message.Length - 1);
|
|
// //System.Windows.Forms.MessageBox.Show(message);
|
|
|
|
//}
|
|
//else
|
|
//{
|
|
// MessageBox.Show("文件读取成功!\n\r已在" + filePath + "下\n\r读取了 0 张Sheet工作表");
|
|
//}
|
|
if (_readSheetName == null || _readSheetName.Count == 0)
|
|
{
|
|
MessageBox.Show("文件读失败,未找到符合的系统要求的工作表!");
|
|
}
|
|
}
|
|
else
|
|
{
|
|
//MessageBox.Show("文件读取失败!\n\r已在" + filePath + "下\n\r读取了 0 张Sheet工作表\n\r请稍后在试!");
|
|
MessageBox.Show("文件读取失败,请联系管理员!");
|
|
}
|
|
}
|
|
|
|
private void ReadExcelToDataSet()
|
|
{
|
|
OleDbConnection connExcel = null;
|
|
try
|
|
{
|
|
_readSheetName = new List<string>();
|
|
_dsExcel = new DataSet();
|
|
|
|
var connString = "";
|
|
if (_fileExt.ToUpper() == ".XLSX")
|
|
{
|
|
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + _filePath +
|
|
";Extended Properties='Excel 12.0;HDR=YES;IMEX=1'";
|
|
}
|
|
else
|
|
{
|
|
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = " + _filePath +
|
|
";Extended Properties = 'Excel 8.0;HDR=YES;IMEX=1'";
|
|
}
|
|
connExcel = new OleDbConnection(connString);
|
|
connExcel.Open();
|
|
var dtSheetNames = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,
|
|
new object[] { null, null, null, "TABLE" });
|
|
var sqlExcel = "";
|
|
OleDbDataAdapter myCommand = null;
|
|
var tableName = "";
|
|
var selectTable = "";
|
|
if (_sheetNames != null && _sheetNames.Count > 0)
|
|
{
|
|
foreach (var sheetName in _sheetNames)
|
|
{
|
|
Debug.Assert(dtSheetNames != null, "dtSheetNames != null");
|
|
for (var i = 0; i < dtSheetNames.Rows.Count; i++)
|
|
{
|
|
var res = 0;
|
|
tableName = dtSheetNames.Rows[i]["TABLE_NAME"].ToString().Replace("'", "").Replace("$", "");
|
|
selectTable = dtSheetNames.Rows[i]["TABLE_NAME"].ToString();
|
|
if (tableName.Length <= 4 || tableName.Equals("_xlnm#_FilterDatabase") ||
|
|
!int.TryParse(tableName.Substring(0, 4), out res) ||
|
|
tableName.IndexOf("_", StringComparison.Ordinal) == (tableName.Length - 1) ||
|
|
tableName.IndexOf("FilterDatabase", StringComparison.Ordinal) != -1) continue;
|
|
if (!(tableName.Replace("'", "").Replace("$", "")).Equals(sheetName)) continue;
|
|
sqlExcel = string.Format(" select * from [" + selectTable + "]");
|
|
myCommand = new OleDbDataAdapter(sqlExcel, connString);
|
|
myCommand.Fill(_dsExcel, tableName);
|
|
RemoveEmptyRow(_dsExcel.Tables[tableName]);
|
|
_readSheetName.Add(tableName);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
else
|
|
{
|
|
Debug.Assert(dtSheetNames != null, "dtSheetNames != null");
|
|
for (var i = 0; i < dtSheetNames.Rows.Count; i++)
|
|
{
|
|
var res = 0;
|
|
tableName = dtSheetNames.Rows[i]["TABLE_NAME"].ToString().Replace("'", "").Replace("$", "");
|
|
selectTable = dtSheetNames.Rows[i]["TABLE_NAME"].ToString();
|
|
if (tableName.Length <= 4 || tableName.Equals("_xlnm#_FilterDatabase") ||
|
|
!int.TryParse(tableName.Substring(0, 4), out res) ||
|
|
tableName.IndexOf("_", StringComparison.Ordinal) == (tableName.Length - 1) ||
|
|
tableName.IndexOf("FilterDatabase", StringComparison.Ordinal) != -1) continue;
|
|
sqlExcel = string.Format(" select * from [" + selectTable + "]");
|
|
myCommand = new OleDbDataAdapter(sqlExcel, connString);
|
|
myCommand.Fill(_dsExcel, tableName);
|
|
RemoveEmptyRow(_dsExcel.Tables[tableName]);
|
|
_readSheetName.Add(tableName);
|
|
}
|
|
}
|
|
connExcel.Close();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
MessageBox.Show(ex.Message);
|
|
}
|
|
finally
|
|
{
|
|
if (connExcel != null)
|
|
{
|
|
connExcel.Close();
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
private void ReadToDataTable()
|
|
{
|
|
OleDbConnection connExcel = null;
|
|
try
|
|
{
|
|
_readSheetName = new List<string>();
|
|
_dsExcel = new DataSet();
|
|
var connString = "";
|
|
if (_fileExt.ToUpper() == ".XLSX")
|
|
{
|
|
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + _filePath +
|
|
";Extended Properties='Excel 12.0;HDR=YES;IMEX=1'";
|
|
}
|
|
else
|
|
{
|
|
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = " + _filePath +
|
|
";Extended Properties = 'Excel 8.0;HDR=YES;IMEX=1'";
|
|
}
|
|
connExcel = new OleDbConnection(connString);
|
|
connExcel.Open();
|
|
var dtSheetNames = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,
|
|
new object[] { null, null, null, "TABLE" });
|
|
|
|
var sqlExcel = "";
|
|
OleDbDataAdapter myCommand = null;
|
|
var tableName = "";
|
|
var selectTable = "";
|
|
if (string.IsNullOrEmpty(_sheetName))
|
|
{
|
|
var b = true;
|
|
var i = 0;
|
|
while (b)
|
|
{
|
|
if (dtSheetNames != null)
|
|
{
|
|
tableName = dtSheetNames.Rows[i]["TABLE_NAME"].ToString().Replace("'", "").Replace("$", "");
|
|
selectTable = dtSheetNames.Rows[i]["TABLE_NAME"].ToString();
|
|
}
|
|
// int res;
|
|
if (tableName.Length <= 4
|
|
|| tableName.Equals("_xlnm#_FilterDatabase")
|
|
// || !int.TryParse(tableName.Substring(0, 4), out res)
|
|
|| tableName.IndexOf("_", StringComparison.Ordinal) == (tableName.Length - 1)
|
|
|| tableName.IndexOf("FilterDatabase", StringComparison.Ordinal) != -1
|
|
)
|
|
{
|
|
if (dtSheetNames != null && i < dtSheetNames.Rows.Count)
|
|
{
|
|
i++;
|
|
}
|
|
else
|
|
{
|
|
b = false;
|
|
}
|
|
}
|
|
else
|
|
{
|
|
sqlExcel = string.Format(" select * from [" + selectTable + "]");
|
|
myCommand = new OleDbDataAdapter(sqlExcel, connString);
|
|
myCommand.Fill(_dsExcel, tableName);
|
|
RemoveEmptyRow(_dsExcel.Tables[tableName]);
|
|
_dtExcel = _dsExcel.Tables[0];
|
|
_readSheetName.Add(tableName);
|
|
b = false;
|
|
}
|
|
}
|
|
}
|
|
else
|
|
{
|
|
Debug.Assert(dtSheetNames != null, "dtSheetNames != null");
|
|
for (var i = 0; i < dtSheetNames.Rows.Count; i++)
|
|
{
|
|
tableName = dtSheetNames.Rows[i]["TABLE_NAME"].ToString().Replace("'", "").Replace("$", "");
|
|
selectTable = dtSheetNames.Rows[i]["TABLE_NAME"].ToString();
|
|
if (!(tableName).Equals(_sheetName)) continue;
|
|
sqlExcel = string.Format(" select * from [" + selectTable + "]");
|
|
myCommand = new OleDbDataAdapter(sqlExcel, connString);
|
|
myCommand.Fill(_dsExcel, tableName);
|
|
RemoveEmptyRow(_dsExcel.Tables[tableName]);
|
|
_dtExcel = _dsExcel.Tables[_sheetName];
|
|
_readSheetName.Add(tableName);
|
|
return;
|
|
}
|
|
}
|
|
connExcel.Close();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
MessageBox.Show(ex.Message);
|
|
}
|
|
finally
|
|
{
|
|
if (connExcel != null)
|
|
{
|
|
connExcel.Close();
|
|
}
|
|
}
|
|
}
|
|
|
|
public static void RemoveEmptyRow(DataTable dt)
|
|
{
|
|
if (dt == null || dt.Rows.Count == 0)
|
|
return;
|
|
var isEmpty = true;
|
|
for (var idx = dt.Rows.Count - 1; idx >= 0; idx--)
|
|
{
|
|
var dr = dt.Rows[idx];
|
|
for (var i = 0; i < dt.Columns.Count; i++)
|
|
{
|
|
if (dr[i].ToString().Trim() != string.Empty)
|
|
{
|
|
isEmpty = false;
|
|
}
|
|
}
|
|
if (isEmpty)
|
|
dt.Rows.Remove(dr);
|
|
}
|
|
}
|
|
}
|
|
}
|