Ejemplo n.º 1
0
        /// <summary>
        /// 将ExDataGridView中的数据导出到Excel文件中
        /// </summary>
        /// <param name="gridview">要导出的ExDataGridView</param>
        /// <param name="sheetname">导出的EXCEL的sheet页名称</param>
        /// <returns></returns>
        public static bool DataGridViewToExcel(DataGridView gridview, string sheetname = "sheet1")
        {
            System.Windows.Forms.SaveFileDialog SFD = new System.Windows.Forms.SaveFileDialog();

            string FileName = "";

            if (gridview.Columns.Count == 0)
            {
                throw new Exception("没有可以导出的数据!");
            }

            SFD.Filter = "2003 Excel文件(*.xls)|*.xls|2007 Excel文件(*.xlsx)|*.xlsx";
            SFD.Title  = "导出Excel表";

            if (SFD.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
            {
                return(false);
            }


            FileName = SFD.FileName.ToString().Trim();


            try
            {
                //DataTable dt = Helper.Transformation.Transformation.DataConvert.GetDgvToTable(gridview);
                Helper.Excel.ExcelHelper a = new Helper.Excel.ExcelHelper(FileName);
                if (a.DataGridViewToExcel(gridview, sheetname, true) == -1)
                {
                    throw new Exception("导出出错!");
                }
                a.Dispose();
            }

            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }



            return(true);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 将Excel文件导出到DataTable
        /// </summary>
        /// <param name="sheetname">导出的EXCEL的sheet页名称</param>
        /// <param name="isFirstRowColumn">Excel的第一行是否是DataTable的列名</param>
        /// <returns></returns>
        public static DataTable ExcelToDataTable(string sheetname = "sheet1", Boolean isFirstRowColumn = true)
        {
            System.Windows.Forms.OpenFileDialog SFD = new System.Windows.Forms.OpenFileDialog();
            DataTable dt       = new DataTable();
            string    FileName = "";



            SFD.Filter = "2003 Excel文件(*.xls)|*.xls|2007 Excel文件(*.xlsx)|*.xlsx";
            SFD.Title  = "导出Excel表";

            if (SFD.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
            {
                return(null);
            }


            FileName = SFD.FileName.ToString().Trim();


            try
            {
                //DataTable dt = Helper.Transformation.Transformation.DataConvert.GetDgvToTable(gridview);
                Helper.Excel.ExcelHelper a = new Helper.Excel.ExcelHelper(FileName);

                dt = a.ExcelToDataTable(sheetname, isFirstRowColumn);



                a.Dispose();
            }

            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }



            return(dt);
        }