1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.IO;
- using System.Data;
- using System.Data.OleDb;
- using Microsoft.Win32;
- using System.Runtime.InteropServices;
- using Platform.Common.LogSystem;
- using System.Security.Cryptography;
-
- //add by wangfei 2012/12/14 16:00
- namespace TellerSystem.Library.Ext.TradeExtension
- {
- /// <summary>
- /// 解析文件
- /// </summary>
- public class AnalyzeFile
- {
- #region 变量
- //文件路径
- private string path;
- //Excel的Sheet节点集合
- private List<string> listSheet;
- //Excel按照的版本
- private static string excelVerson;
- //编码方式
- private Encoding txt_EnCode;
- //行分隔符
- private char[] txt_LineSplit;
- //列分隔符
- private char txt_ColSplit;
- private StreamReader txt_FileStream = null;
- //文件流打开标志
- private bool m_OpenFlag = false;
- #endregion
-
- #region 方法
- /// <summary>
- /// 解析文本文件导入数据
- /// </summary>
- /// <param name="txt_RowSplit">行分隔符</param>
- /// <param name="txt_ColumnSlit">列分割符</param>
- /// <param name="txt_EnCode">编码方式</param>
- /// <param name="isColumnHeader">是否显示列头</param>
- /// <returns>返回一个DataTable</returns>
- public DataTable AnalyzeTxtData(char[] txt_RowSplit, char txt_ColumnSlit, string txt_EnCode, bool isColumnHeader = true)
- {
- DataTable dataTabel = null;
- m_OpenFlag = true;
- //匹配标志
- bool flag = false;
- //当前行数
- int rowCount = 0;
- List<string> lineData = new List<string>();
- if (txt_RowSplit == null)//分割符
- {
- return null;
- }
- if (txt_RowSplit.Length == 0)//行分割符
- {
- return null;
- }
- if (string.IsNullOrWhiteSpace(txt_ColumnSlit.ToString()))//列分割符
- {
- return null;
- }
- if (string.IsNullOrWhiteSpace(txt_EnCode))//编码方式
- {
- return null;
- }
- OpenFile(out path);
-
- //打开文件读取流
- if (!File.Exists(path))//文件不存在
- {
- return null;
- }
- this.txt_EnCode = Encoding.GetEncoding(txt_EnCode);
- //行分割符字符数组,当前只支持最大两个字符的分隔符
- char[] tmpStrs = txt_RowSplit;
- byte[] lineByte = new byte[tmpStrs.Length];
- for (int k = 0; k < tmpStrs.Length; k++)
- {
- lineByte[k] = Convert.ToByte(Convert.ToInt32(tmpStrs[k]));
- }
- this.txt_LineSplit = this.txt_EnCode.GetChars(lineByte);
-
- //列分割符
- byte[] fieldByte = new byte[1];
- char[] fieldSplit = new char[1];
- fieldByte[0] = Convert.ToByte(Convert.ToInt32(txt_ColumnSlit));
- fieldSplit = this.txt_EnCode.GetChars(fieldByte);
- this.txt_ColSplit = fieldSplit[0];
- txt_FileStream = new StreamReader(path, this.txt_EnCode, true);
- char temp;
- StringBuilder rowData = new StringBuilder();
- int readCount = 0;
- //循环处理所有流数据
- while (!txt_FileStream.EndOfStream)
- {
- //当前处理字符
- temp = (char)txt_FileStream.Read();
- readCount++;
- //当前为第二个字符匹配时执行
- if (flag)
- {
- //匹配不成功
- if (temp != this.txt_LineSplit[1])
- {
- rowData.Append(this.txt_LineSplit[0]);
- rowData.Append(temp);
- flag = false;
- //不是最后一个字符
- if (!txt_FileStream.EndOfStream)
- {
- continue;
- }
- }
- //匹配成功
- else
- {
- flag = false;
- }
- }
- else
- {
- //第一个字符匹配成功设置匹配成功标志
- if (temp == this.txt_LineSplit[0])
- {
- //两个字符的情况
- if (this.txt_LineSplit.Length == 2)
- {
- flag = true;
- //不是最后一个字符
- if (!txt_FileStream.EndOfStream)
- {
- continue;
- }
- else
- {
- rowData.Append(temp);
- }
- }
- }
- //第一个匹配不成功时按正常数据处理
- else
- {
- rowData.Append(temp);
- flag = false;
- //不是最后一个字符
- if (!txt_FileStream.EndOfStream)
- {
- if (readCount > 100000)
- {
- throw new Exception("找到不到指定的行分割符");
- }
- continue;
- }
- }
- }
- lineData.Add(rowData.ToString());
- rowData.Clear();
- //设置当前行数
- rowCount += 1;
- //行读取字符个数 清零
- readCount = 0;
- }
- //第一行是否为字段名称
- DataTable data = new DataTable("Table_Sheet1");
- if (isColumnHeader)
- {
- //处理第一行数据位列头
- lineData[0].Split(this.txt_ColSplit).ToList().ForEach
- (
- s =>
- {
- data.Columns.Add(s.Trim());
-
- });
- lineData.Remove(lineData[0]);
- for (int i = 0; i < lineData.Count; i++)
- {
- DataRow dr = data.NewRow();
- var _s = lineData[i].Split(this.txt_ColSplit);
- for (int j = 0; j < _s.Count(); j++)
- {
- dr[j] = _s[j].ToString();
- }
- data.Rows.Add(dr);//在表中添加数据
- }
- }
- else
- {
- //处理第一行数据位列头
- for (int i = 0; i < lineData[0].Split(this.txt_ColSplit).ToList().Count; i++)
- {
- data.Columns.Add("col" + i);
- }
- for (int i = 0; i < lineData.Count; i++)
- {
- DataRow dr = data.NewRow();
- var _s = lineData[i].Split(this.txt_ColSplit);
- for (int j = 0; j < _s.Count(); j++)
- {
- if (j >= data.Columns.Count)
- {
- data.Columns.Add("col" + j);
- }
- dr[j] = _s[j].ToString();
- }
- data.Rows.Add(dr);//在表中添加数据
- }
- }
- dataTabel = data;
- return dataTabel;
- }
-
-
- /// <summary>
- /// 解析文本文件导入数据
- /// </summary>
- /// <param name="txt_RowSplit">行分隔符</param>
- /// <param name="txt_ColumnSlit">列分割符</param>
- /// <param name="txt_EnCode">编码方式</param>
- /// <param name="isColumnHeader">是否显示列头</param>
- /// <returns>返回一个DataTable</returns>
- public List<DataTable> AnalyzeTxtData(bool multiSelect, char[] txt_RowSplit, char txt_ColumnSlit, string txt_EnCode, bool isColumnHeader = true)
- {
- List<DataTable> tableList = new List<DataTable>();
- m_OpenFlag = true;
- //匹配标志
- bool flag = false;
- //当前行数
- int rowCount = 0;
- List<string> lineData = new List<string>();
- if (txt_RowSplit == null)//分割符
- {
- return null;
- }
- if (txt_RowSplit.Length == 0)//行分割符
- {
- return null;
- }
- if (string.IsNullOrWhiteSpace(txt_EnCode))//编码方式s
- {
- return null;
- }
- OpenFile(multiSelect, out path);
- if (!string.IsNullOrEmpty(path))
- {
- StringReader reader = new StringReader(path);
- string tempPath = reader.ReadLine();
- while (tempPath != null)
- {
- if (!File.Exists(tempPath))//文件不存在
- {
- return null;
- }
- lineData.Clear();
- this.txt_EnCode = Encoding.GetEncoding(txt_EnCode);
- //行分割符字符数组,当前只支持最大两个字符的分隔符
- char[] tmpStrs = txt_RowSplit;
- byte[] lineByte = new byte[tmpStrs.Length];
- for (int k = 0; k < tmpStrs.Length; k++)
- {
- lineByte[k] = Convert.ToByte(Convert.ToInt32(tmpStrs[k]));
- }
- this.txt_LineSplit = this.txt_EnCode.GetChars(lineByte);
-
- //列分割符
- byte[] fieldByte = new byte[1];
- char[] fieldSplit = new char[1];
- fieldByte[0] = Convert.ToByte(Convert.ToInt32(txt_ColumnSlit));
- fieldSplit = this.txt_EnCode.GetChars(fieldByte);
- this.txt_ColSplit = fieldSplit[0];
- txt_FileStream = new StreamReader(tempPath, this.txt_EnCode, true);
- char temp;
- StringBuilder rowData = new StringBuilder();
- int readCount = 0;
- //循环处理所有流数据
- while (!txt_FileStream.EndOfStream)
- {
- //当前处理字符
- temp = (char)txt_FileStream.Read();
- readCount++;
- //当前为第二个字符匹配时执行
- if (flag)
- {
- //匹配不成功
- if (temp != this.txt_LineSplit[1])
- {
- rowData.Append(this.txt_LineSplit[0]);
- rowData.Append(temp);
- flag = false;
- //不是最后一个字符
- if (!txt_FileStream.EndOfStream)
- {
- continue;
- }
- }
- //匹配成功
- else
- {
- flag = false;
- }
- }
- else
- {
- //第一个字符匹配成功设置匹配成功标志
- if (temp == this.txt_LineSplit[0])
- {
- //两个字符的情况
- if (this.txt_LineSplit.Length == 2)
- {
- flag = true;
- //不是最后一个字符
- if (!txt_FileStream.EndOfStream)
- {
- continue;
- }
- else
- {
- rowData.Append(temp);
- }
- }
- }
- //第一个匹配不成功时按正常数据处理
- else
- {
- rowData.Append(temp);
- flag = false;
- //不是最后一个字符
- if (!txt_FileStream.EndOfStream)
- {
- if (readCount > 100000)
- {
- throw new Exception("找到不到指定的行分割符");
- }
- continue;
- }
- }
- }
- lineData.Add(rowData.ToString());
- rowData.Clear();
- //设置当前行数
- rowCount += 1;
- //行读取字符个数 清零
- readCount = 0;
- }
- //第一行是否为字段名称
- DataTable data = new DataTable("Table_Sheet1");
- if (isColumnHeader)
- {
- //处理第一行数据位列头
- lineData[0].Split(this.txt_ColSplit).ToList().ForEach
- (
- s =>
- {
- data.Columns.Add(s.Trim());
-
- });
- lineData.Remove(lineData[0]);
- for (int i = 0; i < lineData.Count; i++)
- {
- DataRow dr = data.NewRow();
- var _s = lineData[i].Split(this.txt_ColSplit);
- for (int j = 0; j < _s.Count(); j++)
- {
- dr[j] = _s[j].ToString();
- }
- data.Rows.Add(dr);//在表中添加数据
- }
- }
- else
- {
- //处理第一行数据位列头
- for (int i = 0; i < lineData[0].Split(this.txt_ColSplit).ToList().Count; i++)
- {
- data.Columns.Add("col" + i);
- }
- for (int i = 0; i < lineData.Count; i++)
- {
- DataRow dr = data.NewRow();
- var _s = lineData[i].Split(this.txt_ColSplit);
- for (int j = 0; j < _s.Count(); j++)
- {
- if (j >= data.Columns.Count)
- {
- data.Columns.Add("col" + j);
- }
- dr[j] = _s[j].ToString();
- }
- data.Rows.Add(dr);//在表中添加数据
- }
- }
- data.TableName = tempPath.Substring(tempPath.LastIndexOf('\\') + 1);
- tableList.Add(data);
- tempPath = reader.ReadLine();
- }
- }
- return tableList;
- }
-
- #region 代付业务解密文件的方法
- private const int BUFFER_SIZE = 128 * 1024;
- private const ulong FC_TAG = 0xFC010203040506CF;
- /// <summary>
- ///
- /// </summary>
- /// <param name="password">密码</param>
- /// <param name="salt"></param>
- /// <returns>加密对象</returns>
- private static SymmetricAlgorithm CreateRijndael(string password, byte[] salt)
- {
- PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, salt, "SHA256", 1000);
- SymmetricAlgorithm sma = Rijndael.Create();
- sma.KeySize = 256;
- sma.Key = pdb.GetBytes(32);
- sma.Padding = PaddingMode.PKCS7;
- return sma;
- }
- /// <summary>
- /// 检验两个Byte数组是否相同
- /// </summary>
- /// <param name="b1">Byte数组</param>
- /// <param name="b2">Byte数组</param>
- /// <returns>true-相等</returns>
- private static bool CheckByteArrays(byte[] b1, byte[] b2)
- {
- if (b1.Length == b2.Length)
- {
- for (int i = 0; i < b1.Length; ++i)
- {
- if (b1[i] != b2[i])
- return false;
- }
- return true;
- }
- return false;
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="filePath"></param>
- /// <returns></returns>
- private DataSet EcxelToDataSet(string filePath)
- {
- this.CheckExcelVersion(out excelVerson);//检查Excel版本
- this.GetSheets(out listSheet, filePath); //获取Excel的Sheet节点
-
- string connString = ExcelConnString(excelVerson, filePath); //连接字符串
- OleDbConnection OleConn = new OleDbConnection(connString); //连接Excel
- string sql = " SELECT * FROM [" + listSheet.FirstOrDefault() + "]";
- DataSet data = new DataSet();
- try
- {
- //打开连接
- OleConn.Open();
- //执行查询
- OleDbDataAdapter OleDaExcel = new OleDbDataAdapter(sql, OleConn);
- OleDaExcel.Fill(data, "Sheet1");
-
- //关闭连接
- OleConn.Close();
- }
- catch (Exception ex)
- {
- //关闭连接
- PlatformLogger.SystemErrorInfo("解析Excel文件发生异常:", ex);
- OleConn.Close();
- }
- return data;
- }
-
- /// <summary>
- /// 解析加密过的Excel文件
- /// </summary>
- /// <param name="password"></param>
- /// <returns></returns>
- public DataTable AnalyseEncryptExcelData(string password, ref string fileID)
- {
- DataTable dataTable = new DataTable();
-
- this.OpenFile(out path, "Files|*.txt;"); //打开文件提示框
- if (string.IsNullOrEmpty(path)) return dataTable;
- //去掉前100字节的明文信息
- byte[] data = File.ReadAllBytes(path);
- string newfile = path.Substring(0, path.Length - 4);
- //获取文件唯一ID
- byte[] guidB = new byte[32];
- Array.Copy(data, 100, guidB, 0, 32);
- fileID = Encoding.Default.GetString(guidB);
-
- FileStream foutN = File.OpenWrite(newfile);
- foutN.Write(data, 132, data.Length - 132);
- foutN.Close();
- var outimp = path.Substring(0, path.LastIndexOf(".")) + ".xlsx";
-
- using (FileStream fin = File.OpenRead(newfile), fout = File.OpenWrite(outimp))
- {
- int size = (int)fin.Length;
- byte[] bytes = new byte[BUFFER_SIZE];
- int read = -1;
- int value = 0;
- int outValue = 0;
- byte[] IV = new byte[16];
- fin.Read(IV, 0, 16);
- byte[] salt = new byte[16];
- fin.Read(salt, 0, 16);
- SymmetricAlgorithm sma = CreateRijndael(password, salt);
- sma.IV = IV;
- value = 32;
- long lSize = -1;
- // 创建散列对象, 校验文件
- HashAlgorithm hasher = SHA256.Create();
- using (CryptoStream cin = new CryptoStream(fin, sma.CreateDecryptor(), CryptoStreamMode.Read),
- chash = new CryptoStream(Stream.Null, hasher, CryptoStreamMode.Write))
- {
- // 读取文件长度
- BinaryReader br = new BinaryReader(cin, Encoding.UTF8);
- lSize = br.ReadInt64();
- ulong tag = br.ReadUInt64();
- if (FC_TAG != tag)
- return dataTable;
- long numReads = lSize / BUFFER_SIZE;
- long slack = (long)lSize % BUFFER_SIZE;
- for (int i = 0; i < numReads; ++i)
- {
- read = cin.Read(bytes, 0, bytes.Length);
- fout.Write(bytes, 0, read);
- chash.Write(bytes, 0, read);
- value += read;
- outValue += read;
- }
- if (slack > 0)
- {
- read = cin.Read(bytes, 0, (int)slack);
- fout.Write(bytes, 0, read);
- chash.Write(bytes, 0, read);
- value += read;
- outValue += read;
- }
- chash.Flush();
- chash.Close();
- fout.Flush();
- fout.Close();
- byte[] curHash = hasher.Hash;
- // 获取比较和旧的散列对象
- byte[] oldHash = new byte[hasher.HashSize / 8];
- read = cin.Read(oldHash, 0, oldHash.Length);
- if ((oldHash.Length != read) || (!CheckByteArrays(oldHash, curHash)))
- return dataTable;
- }
- if (outValue != lSize)
- return dataTable;
- }
- dataTable = EcxelToDataSet(outimp).Tables[0];
- File.Delete(outimp);
- //删除表中的所有空行,删除
- if (dataTable != null)
- {
- bool canDel;
- for (int i = 0; i < dataTable.Rows.Count; i++)
- {
- canDel = true;
- for (int j = 0; j < dataTable.Columns.Count; j++)
- {
- if (dataTable.Rows[i][j].ToString().Trim() == string.Empty)
- {
- }
- else
- {
- canDel = false;
- dataTable.Rows[i][j] = dataTable.Rows[i][j].ToString().Replace(" ", "").Replace(" ", "");
- }
- }
- if (canDel)
- {
- dataTable.Rows[i].Delete();
- }
- }
- dataTable.AcceptChanges();
- }
- //删除新建文件
- File.Delete(newfile);
- return dataTable;
- }
- #endregion
-
- /// <summary>
- /// 解析Excel文件导入的数据
- /// </summary>
- /// <param name="RowCount">可选参数 RowCount=0-默认解析全部行</param>
- /// <param name="columnCount">可选参数 ColumnCount=0-默认解析全部列</param>
- /// <returns>返回DataTable</returns>
- public DataTable AnalyseExcelData(int RowCount = 0, int columnCount = 0)
- {
- DataTable dataTable = null;
- this.OpenFile(out path, "Excel Files|*.xlsx;*.xls;"); //打开文件提示框
- this.CheckExcelVersion(out excelVerson);//检查Excel版本
- this.GetSheets(out listSheet); //获取Excel的Sheet节点
- if (path != null && path.Trim().Length > 0)
- {
- string connString = ExcelConnString(excelVerson, path); //连接字符串
- OleDbConnection OleConn = new OleDbConnection(connString); //连接Excel
- string sql = " SELECT * FROM [" + listSheet.FirstOrDefault() + "$]";//查询字符串
- DataSet data = new DataSet();
- try
- {
- //打开连接
- OleConn.Open();
- //执行查询
- OleDbDataAdapter OleDaExcel = new OleDbDataAdapter(sql, OleConn);
- OleDaExcel.Fill(data, "Sheet1");
- dataTable = data.Tables[0];
- dataTable.TableName = path.Substring(path.LastIndexOf('\\') + 1);
- if (RowCount > 0 && columnCount > 0)
- {
- DataTable dt = new DataTable(dataTable.TableName);
- DataColumnCollection colums = data.Tables[0].Columns;
- //处理第一行数据
- for (int i = 0; i < columnCount; i++)
- {
- dt.Columns.Add(colums[i].ToString());
- }
- for (int i = 0; i < RowCount; i++)
- {
- DataRow dr = dt.NewRow();
- for (int j = 0; j < columnCount; j++)
- {
- dr[j] = dataTable.Rows[i][j].ToString();
- }
- dt.Rows.Add(dr);//想表中添加数据
- }
- dataTable = null;
- dataTable = dt;
- }
- //关闭连接
- OleConn.Close();
- }
- catch (Exception ex)
- {
- //关闭连接
- PlatformLogger.SystemErrorInfo("解析Excel文件发生异常:", ex);
- OleConn.Close();
- //写错误日志
-
- }
- }
- //删除表中的所有空行
- //if (dataTable != null)
- //{
- // bool canDel = false;
- // for (int i = 0; i < dataTable.Rows.Count; i++)
- // {
- // for (int j = 0; j < dataTable.Columns.Count; j++)
- // {
- // if (dataTable.Rows[i][j].ToString() == string.Empty)
- // {
- // canDel = true;
- // }
- // else
- // {
- // canDel = false;
- // break;
- // }
- // }
- // if (canDel)
- // {
- // dataTable.Rows[i].Delete();
- // }
- // }
- // dataTable.AcceptChanges();
- //}
- //删除表中的所有空行,删除
- if (dataTable != null)
- {
- bool canDel;
- for (int i = 0; i < dataTable.Rows.Count; i++)
- {
- canDel = true;
- for (int j = 0; j < dataTable.Columns.Count; j++)
- {
- if (dataTable.Rows[i][j].ToString().Trim() == string.Empty)
- {
- }
- else
- {
- canDel = false;
- dataTable.Rows[i][j] = dataTable.Rows[i][j].ToString().Replace(" ", "").Replace(" ", "");
- }
- }
- if (canDel)
- {
- dataTable.Rows[i].Delete();
- }
- }
- dataTable.AcceptChanges();
- }
- return dataTable;
- }
- #endregion
-
- #region 私有方法
- /// <summary>
- /// 取得Excel文件的所有信息
- /// </summary>
- /// <param name="outSheets">返回所有Sheet信息</param>
- private void GetSheets(out List<string> outSheets)
- {
- //连接字符串
- string connString = ExcelConnString(excelVerson, path);
- DataTable tableInfo;
- List<string> oList = new List<string>();
- string tmpstr = "";
- try
- {
- OleDbConnection objConn = new OleDbConnection(connString);
- //打开连接
- objConn.Open();
- tableInfo = objConn.GetSchema("TABLES");
- //处理所有SHEET信息
- for (int i = 0; i < tableInfo.Rows.Count; i++)
- {
- tmpstr = tableInfo.Rows[i]["TABLE_NAME"].ToString();
- if (tmpstr.LastIndexOf('$') == tmpstr.Length - 1)
- {
- oList.Add(tmpstr.Trim().TrimEnd('$'));
- }
- }
- //关闭连接
- objConn.Close();
- }
- catch (Exception ex)
- {
- PlatformLogger.SystemErrorInfo("解析Excel文件发生异常:", ex);
- //写错误日志
- }
- //返回值
- outSheets = oList;
- }
-
- /// <summary>
- /// 取得Excel文件的所有信息
- /// </summary>
- /// <param name="outSheets">返回所有Sheet信息</param>
- private void GetSheets(out List<string> outSheets, string path)
- {
- //连接字符串
- string connString = ExcelConnString(excelVerson, path);
- DataTable tableInfo;
- List<string> oList = new List<string>();
- string tmpstr = "";
- try
- {
- OleDbConnection objConn = new OleDbConnection(connString);
- //打开连接
- objConn.Open();
- tableInfo = objConn.GetSchema("TABLES");
- //处理所有SHEET信息
- for (int i = 0; i < tableInfo.Rows.Count; i++)
- {
- tmpstr = tableInfo.Rows[i]["TABLE_NAME"].ToString();
- //这种判断方式是错误的,因为sheet页标签的名字很可能是全数字,解析的结果就是数字+$+’
- //if (tmpstr.LastIndexOf('$') == tmpstr.Length - 1)
- //{
- // oList.Add(tmpstr.Trim().TrimEnd('$'));
- //}
- oList.Add(tmpstr);
- }
- //关闭连接
- objConn.Close();
- }
- catch (Exception ex)
- {
- PlatformLogger.SystemErrorInfo("解析Excel文件发生异常:", ex);
- //写错误日志
- }
- //返回值
- outSheets = oList;
- }
- /// <summary>
- /// 检查本地Excel版本
- /// </summary>
- /// <returns>Excel版本号</returns>
- private string CheckExcelVersion(out string ExcelVersion)
- {
- ExcelVersion = string.Empty;
- string path03 = string.Empty;
- string path07 = string.Empty;
- string path10 = string.Empty;
- string path13 = string.Empty;
- if (Environment.Is64BitOperatingSystem) //64位系统
- {
- path03 = Get64BitRegistryKey(@"SOFTWARE\\Microsoft\\Office\\11.0\\Excel\\InstallRoot\\", "Path");
- if (string.IsNullOrEmpty(path03)) //如果未取到,可能是64系统装的32位office,需取32位注册表
- {
- path03 = Get32BitRegistryKey(@"SOFTWARE\\Microsoft\\Office\\11.0\\Excel\\InstallRoot\\", "Path");
- }
- path07 = Get64BitRegistryKey(@"SOFTWARE\\Microsoft\\Office\\12.0\\Excel\\InstallRoot\\", "Path");
- if (string.IsNullOrEmpty(path07))//如果未取到,可能是64系统装的32位office,需取32位注册表
- {
- path07 = Get32BitRegistryKey(@"SOFTWARE\\Microsoft\\Office\\12.0\\Excel\\InstallRoot\\", "Path");
- }
- path10 = Get64BitRegistryKey(@"SOFTWARE\\Microsoft\\Office\\14.0\\Excel\\InstallRoot\\", "Path");
- if (string.IsNullOrEmpty(path10))//如果未取到,可能是64系统装的32位office,需取32位注册表
- {
- path10 = Get32BitRegistryKey(@"SOFTWARE\\Microsoft\\Office\\14.0\\Excel\\InstallRoot\\", "Path");
- }
- path13 = Get64BitRegistryKey(@"SOFTWARE\\Microsoft\\Office\\15.0\\Excel\\InstallRoot\\", "Path");
- if (string.IsNullOrEmpty(path13))//如果未取到,可能是64系统装的32位office,需取32位注册表
- {
- path13 = Get32BitRegistryKey(@"SOFTWARE\\Microsoft\\Office\\15.0\\Excel\\InstallRoot\\", "Path");
- }
- }
- else //32位系统
- {
- path03 = Get32BitRegistryKey(@"SOFTWARE\\Microsoft\\Office\\11.0\\Excel\\InstallRoot\\", "Path");
- path07 = Get32BitRegistryKey(@"SOFTWARE\\Microsoft\\Office\\12.0\\Excel\\InstallRoot\\", "Path");
- path10 = Get32BitRegistryKey(@"SOFTWARE\\Microsoft\\Office\\14.0\\Excel\\InstallRoot\\", "Path");
- path13 = Get32BitRegistryKey(@"SOFTWARE\\Microsoft\\Office\\15.0\\Excel\\InstallRoot\\", "Path");
- }
- //检查本机是否安装Office2003
- if (File.Exists(path03 + "EXCEL.exe"))
- {
- ExcelVersion = "8.0";
- }
-
- //检查本机是否安装Office2007
-
- if (File.Exists(path07 + "EXCEL.exe"))
- {
- ExcelVersion = "12.0";
- }
- //检查本机是否安装Office2010
-
- if (File.Exists(path10 + "EXCEL.exe"))
- {
- ExcelVersion = "12.0";
- }
- //检查本机是否安装Office2013
-
- if (File.Exists(path13 + "EXCEL.exe"))
- {
- ExcelVersion = "12.0";
- }
- //如果在注册表中找不到安装目录,设置初始值
- if (string.IsNullOrEmpty(ExcelVersion))
- {
- ExcelVersion = "12.0";
- }
- return ExcelVersion;
- }
- #region 32位程序读取64位系统注册表(HKEY_LOCAL_MACHINE目录)
-
- // 关闭64位(文件系统)的操作转向
- [DllImport("Kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
- private static extern bool Wow64DisableWow64FsRedirection(ref IntPtr ptr);
- // 开启64位(文件系统)的操作转向
- [DllImport("Kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
- private static extern bool Wow64RevertWow64FsRedirection(IntPtr ptr);
-
- // 获取操作Key值句柄
- [DllImport("Advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
- private static extern uint RegOpenKeyEx(UIntPtr hKey, string lpSubKey, uint ulOptions,
- int samDesired, out IntPtr phkResult);
- //关闭注册表转向(禁用特定项的注册表反射)
- [DllImport("Advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
- private static extern long RegDisableReflectionKey(IntPtr hKey);
- //使能注册表转向(开启特定项的注册表反射)
- [DllImport("Advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
- private static extern long RegEnableReflectionKey(IntPtr hKey);
- //获取Key值(即:Key值句柄所标志的Key对象的值)
- [DllImport("Advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
- private static extern int RegQueryValueEx(IntPtr hKey, string lpValueName, int lpReserved,
- out uint lpType, System.Text.StringBuilder lpData,
- ref uint lpcbData);
- private string Get64BitRegistryKey(string subKeyName, string keyName)
- {
- int KEY_QUERY_VALUE = (0x0001);
- int KEY_WOW64_64KEY = (0x0100);
- int KEY_ALL_WOW64 = (KEY_QUERY_VALUE | KEY_WOW64_64KEY);
- try
- {
- //将Windows注册表主键名转化成为不带正负号的整形句柄(与平台是32或者64位有关)
- UIntPtr hKey = (UIntPtr)0x80000002;
- //声明将要获取Key值的句柄
- IntPtr pHKey = IntPtr.Zero;
- //记录读取到的Key值
- StringBuilder result = new StringBuilder(1024);
- uint resultSize = 1024;
- uint lpType = 0;
- //关闭文件系统转向
- IntPtr oldWOW64State = new IntPtr();
- if (Wow64DisableWow64FsRedirection(ref oldWOW64State))
- {
- //获得操作Key值的句柄
- RegOpenKeyEx(hKey, subKeyName, 0, KEY_ALL_WOW64, out pHKey);
-
- //关闭注册表转向(禁止特定项的注册表反射)
- RegDisableReflectionKey(pHKey);
-
- //获取访问的Key值
- RegQueryValueEx(pHKey, keyName, 0, out lpType, result, ref resultSize);
-
- //打开注册表转向(开启特定项的注册表反射)
- RegEnableReflectionKey(pHKey);
- }
- //打开文件系统转向
- Wow64RevertWow64FsRedirection(oldWOW64State);
- //返回Key值
- return result.ToString().Trim();
- }
- catch (Exception ex)
- {
- //写错误日志
- PlatformLogger.SystemErrorInfo("解析Excel文件发生异常:", ex);
- return string.Empty;
- }
- }
-
- #endregion
- #region 32位程序读取32位系统注册表(HKEY_LOCAL_MACHINE目录)
- private string Get32BitRegistryKey(string subKeyName, string keyName)
- {
- string result = string.Empty;
- RegistryKey rk = Registry.LocalMachine;
- RegistryKey key = rk.OpenSubKey(subKeyName);
- if (key != null)
- {
- result = key.GetValue(keyName).ToString();
- }
- return result;
- }
- #endregion
-
-
-
-
- /// <summary>
- /// 连接Excel的字符串
- /// </summary>
- /// <param name="filePath"></param>
- /// <returns>连接Excel的字符串</returns>
- private string ExcelConnString(string excelVerson, string filePath)
- {
- string _excelConnString = "";
- if (excelVerson == "8.0")
- {
- _excelConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=Yes'";
- }
- if (excelVerson == "12.0")
- {
- _excelConnString = "Provider=Microsoft.Ace.OleDb.12.0;Data Source=" + filePath + ";Extended Properties='Excel 12.0;HDR=Yes'";
- }
- return _excelConnString;
- }
-
- /// <summary>
- /// 调用Win32打开提示框,选择文件
- /// </summary>
- /// <param name="path">返回文件的路径</param>
- /// <param name="filter">提示框可选择文件的后缀</param>
- private void OpenFile(out string path, string filter = "txt Files|*.txt")
- {
- path = "";
- OpenFileDialog fileDialog = new OpenFileDialog();
- fileDialog.Title = "上传文件";
- fileDialog.FileName = String.Empty;
- fileDialog.Filter = filter;
- fileDialog.Multiselect = false;
- if (fileDialog.ShowDialog() == true)
- {
- path = fileDialog.FileName;
- }
- }
-
- /// <summary>
- /// 调用Win32打开提示框,选择文件(支持多选)
- /// </summary>
- /// <param name="path">返回文件的路径</param>
- /// <param name="filter">提示框可选择文件的后缀</param>
- private void OpenFile(bool multiSelect, out string path, string filter = "txt Files|*.txt")
- {
- path = "";
- OpenFileDialog fileDialog = new OpenFileDialog();
- fileDialog.Title = "上传文件";
- fileDialog.FileName = String.Empty;
- fileDialog.Filter = filter;
- fileDialog.Multiselect = multiSelect;
- if (fileDialog.ShowDialog() == true)
- {
- StringBuilder builder = new StringBuilder();
- if (fileDialog.FileNames != null)
- {
- for (int i = 0; i < fileDialog.FileNames.Length; i++)
- {
- builder.AppendLine(fileDialog.FileNames[i]);
- }
- path = builder.ToString();
- }
- }
- }
- #endregion
-
- }
- }
|