using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Linq; using System.Windows.Forms; using DevExpress.XtraBars; using DevExpress.XtraBars.Ribbon; //using DeiNiu.wms.win.utils; using DevExpress.XtraEditors; using DevExpress.XtraEditors.Controls; using DevExpress.XtraGrid.Views.Grid; using DeiNiu.Utils; using System.Data.OleDb; using DeiNiu.wms.win.utils; using System.Configuration; using System.Security.Cryptography; using System.Net; using System.IO; namespace DeiNiu.wms.win { public partial class BasicRibbonForm : DevExpress.XtraBars.Ribbon.RibbonForm { public BasicRibbonForm() { InitializeComponent(); readPrinters(); } protected void showWaitForm(string desc=null) { if (this.splashScreenManager1.IsSplashFormVisible) { return; } closeWaitForm(); try { this.splashScreenManager1.ShowWaitForm(); } catch { } if (!string.IsNullOrEmpty(desc)) { splashScreenManager1.SetWaitFormDescription(desc); } // WaitFormService.Show(this); } protected void closeWaitForm() { if (!this.splashScreenManager1.IsSplashFormVisible) { return; } try { this.splashScreenManager1.CloseWaitForm(); } catch { } // WaitFormService.Close(); } protected struct Colitem { public int key ; public string value ; public override string ToString() { return value; } } protected void initialComboBoxe(ComboBoxEdit combo, Dictionary dic, bool isForQuery = true) { combo.Properties.TextEditStyle = TextEditStyles.DisableTextEditor; combo.Properties.Items.Clear(); ComboBoxItemCollection col = combo.Properties.Items; col.BeginUpdate(); if (isForQuery) { col.Add("全部"); } try { foreach (int key in dic.Keys) { Colitem c = new Colitem(); c.key = key; c.value = dic[key]; col.Add(c); } } finally { col.EndUpdate(); } combo.SelectedIndex = 0; } protected void initialComboBoxe(ComboBoxEdit combo, DataRow[] drss,bool isForQuery =true) { } protected void showErrorMsg(string message) { closeWaitForm(); /* if ( message.Equals(WmsConstants.WCF_UN_AUTH_MESSAGE)) { if (this.ParentForm != null){ ((main)this.ParentForm).showLogin(); } else if (this is main) { ((main)this).showLogin(); } return; }*/ MessageBox.Show(message, "出错了", MessageBoxButtons.OK, MessageBoxIcon.Error); } protected void setupGridView(GridView gridview, bool canMultiSelect,bool showGroupPannel = true,bool canFocus = true) { gridview.OptionsView.EnableAppearanceEvenRow = true; //偶数行颜色变化 gridview.OptionsView.EnableAppearanceOddRow = false; //奇数行颜色变化 gridview.OptionsSelection.MultiSelect = canMultiSelect;// true;// canMultiSelect; //多选模式下,可以高亮选中cell gridview.OptionsView.ShowGroupPanel = showGroupPannel; gridview.OptionsClipboard.CopyColumnHeaders = DevExpress.Utils.DefaultBoolean.False; gridview.OptionsSelection.MultiSelectMode = GridMultiSelectMode.CellSelect; gridview.OptionsBehavior.Editable = false; gridview.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.CellFocus; gridview.OptionsSelection.EnableAppearanceHideSelection = false; // gridview.OptionsSelection.EnableAppearanceFocusedCell = canFocus; // gridview.OptionsSelection.EnableAppearanceFocusedRow = canFocus; // gridview.OptionsSelection.EnableAppearanceHideSelection = true; } //private void GridView_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) //{ // if (e.Control & e.KeyCode == Keys.C) // { // Clipboard.SetDataObject(AdvBandedGridView1.GetFocusedRowCellValue(AdvBandedGridView1.FocusedColumn)); // e.Handled = true; // } //} //显示行的序号 protected void gridView_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e) { if (e.Info.IsRowIndicator && e.RowHandle >= 0) { e.Info.DisplayText = (e.RowHandle + 1).ToString(); } } protected void debug(string msg) { DeiNiu.Utils.LogHelper.debug(this.GetType(), msg); } /// /// 获取GridView过滤或排序后的数据集 /// /// /// public System.Collections.IList GetGridViewFilteredAndSortedData(DevExpress.XtraGrid.Views.Grid.GridView view) { return view.DataController.GetAllFilteredAndSortedRows(); } protected void gridview_LostFocus(object sender, EventArgs e) { switchGridViewRowSelection((GridView)sender, false); } protected void switchGridViewRowSelection(GridView gridView, bool isOn) { // gridView.OptionsSelection.EnableAppearanceFocusedCell = isOn; gridView.OptionsSelection.EnableAppearanceFocusedRow = isOn; gridView.OptionsSelection.EnableAppearanceHideSelection = !isOn; } protected void gridview_GotFocus(object sender, EventArgs e) { switchGridViewRowSelection((GridView)sender, true); } protected void showLogin() { // createMenus(); } protected bool checkPermission(string permision) { return false; } protected string filtRiskChar(string str) //过滤非法字符 { string s = ""; s = str.Replace("'", " "); s = s.Replace(";", " "); s = s.Replace("1=1", " "); s = s.Replace("|", " "); s = s.Replace("<", " "); s = s.Replace(">", " "); s = s.Replace("#", " "); s = s.Replace("insert", " "); s = s.Replace("update", " "); s = s.Replace("delete", " "); s = s.Replace("drop", " "); s = s.Replace("truncate", " "); s = s.Replace("alter", " "); s = s.Replace("create", " "); return s; } protected void showInfoMsg(string message) { closeWaitForm(); MessageBox.Show(message, "通知", MessageBoxButtons.OK, MessageBoxIcon.Information); } string strTitle = "报表"; DataSet ExcelDS = new DataSet(); DataSet lblSelectDs = new DataSet(); // /// 导出按钮 /// /// /// protected void exportExcel(string title ,GridView gvSelectedItems) { showWaitForm(); string strName = ""; try { if (gvSelectedItems.RowCount == 0) { showErrorMsg("Grid表格中没有数据,不能导出为Excel"); return; } DateTime MMSDate = DateTime.Now; using (SaveFileDialog saveFileDialog = new SaveFileDialog()) { saveFileDialog.Filter = "导出Excel(*.xls)|*.xls"; saveFileDialog.FilterIndex = 0; saveFileDialog.RestoreDirectory = true; saveFileDialog.CreatePrompt = true; saveFileDialog.Title = "导出文件保存路径"; //默认的文件名 saveFileDialog.FileName = title + " - " + MMSDate.ToString("yyyyMMdd"); //saveFileDialog.ShowDialog(); if (saveFileDialog.ShowDialog() == DialogResult.OK) { strName = saveFileDialog.FileName; if (strName.Length != 0) { // gridColumn2.Visible = false; // gridItemID2.Visible = true; // gridItemID2.VisibleIndex = 0; gvSelectedItems.ExportToXls(strName); // gridColumn2.Visible = true; // gridItemID2.Visible = false; showInfoMsg("导出Excel成功"); //关闭操作 System.Reflection.Missing miss = System.Reflection.Missing.Value; Microsoft.Office.Interop.Excel.Application objExcel = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook objWorkBook = objExcel.Workbooks.Add(miss); Microsoft.Office.Interop.Excel.Worksheet objSheet = (Microsoft.Office.Interop.Excel.Worksheet)objWorkBook.ActiveSheet; objWorkBook.Close(null, null, null); objExcel.Workbooks.Close(); objExcel.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(objExcel); System.Runtime.InteropServices.Marshal.ReleaseComObject(objWorkBook); System.Runtime.InteropServices.Marshal.ReleaseComObject(objSheet); objSheet = null; objWorkBook = null; objExcel = null; } else { showErrorMsg("保存的Excel名称不能为空"); } } } } catch (System.Exception msg) { // showErrorMsg(msg.ToString()); } finally { GC.Collect(); } } //导入Excel /// /// 导入按钮 /// /// /// protected void importExcel( ) { try { showWaitForm(); OpenFileDialog ofd = new OpenFileDialog(); ofd.Title = "Excel文件"; ofd.FileName = ""; ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); ofd.Filter = "Excel文件(*.xls)|*.xls"; ofd.ValidateNames = true; //文件有效性验证ValidateNames,验证用户输入是否是一个有效的Windows文件名 ofd.CheckFileExists = true; //验证路径有效性 ofd.CheckPathExists = true; //验证文件有效性 string strName = string.Empty; if (ofd.ShowDialog() == DialogResult.OK) { strName = ofd.FileName; } if (strName == "") { return; } if (ReadExcel(strName )) { showInfoMsg("数据导入结束"); //isChanged = true; } else showErrorMsg("数据导入失败,请检查导入的Excel格式与数据是否正确"); this.Cursor = Cursors.Default; } catch (System.Exception Msg) { showErrorMsg("数据导入失败,请检查导入的Excel格式与数据是否正确"); //MessageBoxShow.ShowErrMessage(Msg.ToString()+"数据导入失败,请检查导入的Excel格式与数据是否正确"); } } /// /// Excel数据导入方法 /// /// /// /// public bool ReadExcel(string filePath ) { bool isVailed = false; //根据路径打开一个Excel文件并将数据填充到ds中 try { string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = " + filePath + ";Extended Properties ='Excel 8.0;HDR=YES;IMEX=1'"; OleDbConnection conn = new OleDbConnection(strConn); conn.Open(); string strExcel = ""; OleDbDataAdapter myCommand = null; //获取Excel中的sheet的名称 string SheetName = GetExcelSheetNames(filePath)[0]; //strExcel = "select * from [sheet1$]"; strExcel = "select * from [" + SheetName + "$]"; myCommand = new OleDbDataAdapter(strExcel, strConn); // RealSailing.DataSet.SlipInfo.SLPD010_SLIPSUMHDS ds = new RealSailing.DataSet.SlipInfo.SLPD010_SLIPSUMHDS(); System.Data.DataSet ds = new System.Data.DataSet(); myCommand.Fill(ds, "table1"); conn.Close(); if (ds.Tables["table1"].Rows.Count == 0) { showErrorMsg("要导入的Excel没有数据"); } ExcelDS.Clear(); showWaitForm(); clearOldData(); int testK = 0; for (int j = 0; j < ds.Tables["table1"].Rows.Count; j++) { testK++; //把数据填充到ds中 try { FillDataToDs(ds.Tables["table1"].Rows[j]); isVailed = true; } catch (Exception e) { showErrorMsg(e.Message); MessageBoxButtons messButton = MessageBoxButtons.OKCancel; DialogResult dr = MessageBox.Show("导入数据发生错误,是否继续?", "发生错误", messButton); if (dr == DialogResult.OK) { continue; } else { break; } } } closeWaitForm(); } catch (System.Data.OleDb.OleDbException ex) { showErrorMsg(ex.Message); if (ex.Message.IndexOf("不是一个有效名称。请确认它不包含无效的字符或标点,且名称不太长") != -1) { return false; } return false; } return true; } protected virtual void clearOldData() { } /// /// 获取获得当前你选择的Excel Sheet的所有名字 /// /// /// public static string[] GetExcelSheetNames(string filePath) { Microsoft.Office.Interop.Excel.ApplicationClass excelApp = new Microsoft.Office.Interop.Excel.ApplicationClass(); Microsoft.Office.Interop.Excel.Workbooks wbs = excelApp.Workbooks; Microsoft.Office.Interop.Excel.Workbook wb = wbs.Open(filePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); int count = wb.Worksheets.Count; string[] names = new string[count]; for (int i = 1; i <= count; i++) { names[i - 1] = ((Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[i]).Name; } wb.Close(null, null, null); excelApp.Quit(); wbs.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp); System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp); System.Runtime.InteropServices.Marshal.ReleaseComObject(wbs); excelApp = null; wbs = null; wb = null; return names; } /// /// 处理具体数据 /// 将在各子form重写逻辑 /// /// protected virtual void FillDataToDs(DataRow dr) //string itemid, string itemplu, string itemName) { } //导入导出Excel 注意的是及时的关闭Excel,不然占用进程很麻烦,我调试了大半天太弄好的 /// /// 写入配置信息 /// protected void WriteConfig(string key, string value) { //ShowText("正在写入配置文件!请稍等...."); string appConfigPath = Application.StartupPath + "\\" + Application.ProductName + ".exe"; ConfigurationOperator co = new ConfigurationOperator(appConfigPath, utils.ConfigType.ExeConfig); co.AddAppSetting(key, value); co.Save(); } protected string Encrypt(string password) { Byte[] clearBytes = new UnicodeEncoding().GetBytes(password); Byte[] hashedBytes = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(clearBytes); return BitConverter.ToString(hashedBytes); } protected string getConfigValue(string key) { return System.Configuration.ConfigurationManager.AppSettings[key]; } public void readPrinters() { string printer = getConfigValue("CodePrinter"); WmsConstants.PRINTER_NAME_A4 = getConfigValue("A4Printer"); WmsConstants.PRINTER_NAME_CODE = printer; } /// /// GET请求与获取结果 /// public static string HttpGet(string Url, string postDataStr) { try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (string.IsNullOrEmpty(postDataStr) ? "" : "?") + postDataStr); request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8"; request.Timeout = 10000; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); return retString; } catch (Exception ex) { return ex.Message; } } } }