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

4 years ago
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);
}
}
}
}