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.
|
|
using System; using System.Collections.Generic; using System.Data; using System.Data.OleDb; using System.Windows.Forms; using DevExpress.XtraEditors; using ICSSoft.Base.Config.AppConfig;
namespace ICSSoft.Frame.APP { public partial class FormReadExcel : XtraForm { public DataTable _excelData = null; public string _url = ""; public FormReadExcel() { InitializeComponent(); }
private void txtUrl_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e) { OpenFileDialog of = new OpenFileDialog {Filter = @"excel|*.xls;*.xlsx"}; if (of.ShowDialog() == DialogResult.OK) { txtUrl.Text = of.FileName; txtSheet.Properties.Items.Clear(); txtSheet.Text = ""; string[] strs = GetExcelSheetNames(of.FileName); foreach (string str in strs) { txtSheet.Properties.Items.Add(str); } } }
private void btnOk_Click(object sender, EventArgs e) { if (txtUrl.Text.Trim() == "") return; if (txtSheet.Text.Trim() == "") return; _excelData = AppConfig.GetExcelData(txtUrl.Text, txtSheet.Text.Trim()); _url = txtUrl.Text; DialogResult = DialogResult.OK;
}
private static string[] GetExcelSheetNames(string fileName) { OleDbConnection objConn = null; System.Data.DataTable dt = null; try { string connString; string fileType = fileName.Substring(fileName.LastIndexOf(".")); if (fileType == ".xls") connString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + fileName + ";Extended Properties=Excel 8.0;"; else//.xlsx
connString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\""; // 创建连接对象
objConn = new OleDbConnection(connString); // 打开数据库连接
objConn.Open(); // 得到包含数据架构的数据表
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); if (dt == null) { return null; } List<string> excelSheets = new List<string>();
// 添加工作表名称到字符串数组
foreach (DataRow row in dt.Rows) { string strSheetTableName = row["TABLE_NAME"].ToString(); if (strSheetTableName.EndsWith("'")) { strSheetTableName = strSheetTableName.Substring(1, strSheetTableName.Length - 2); } //过滤无效SheetName
if (strSheetTableName.Contains("$") && strSheetTableName.Replace("'", "").EndsWith("$")) { excelSheets.Add(strSheetTableName.Substring(0, strSheetTableName.Length - 1)); }
} return excelSheets.ToArray(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); return null; } finally { // 清理
if (objConn != null) { objConn.Close(); objConn.Dispose(); } if (dt != null) { dt.Dispose(); } } } } }
|