当前位置:软件学习 > Excel >>

DataGridView按列顺序导出Excel

先添加引用程序集 Microsoft.Office.Interop.Excel

声明 using Excel = Microsoft.Office.Interop.Excel; 

以及贴出方法:


//DataGridView数据导出Excel 
        private void ExportExcel(string fileName, DataGridView myDGV) 
        { 
            string saveFileName = ""; 
            //bool fileSaved = false; 
            SaveFileDialog saveDialog = new SaveFileDialog(); 
            saveDialog.DefaultExt = "xls"; 
            saveDialog.Filter = "Excel文件|*.xls"; 
            saveDialog.FileName = fileName; 
            saveDialog.ShowDialog(); 
            saveFileName = saveDialog.FileName; 
            if (saveFileName.IndexOf(":") < 0)  
                return; //被点了取消  
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); 
            if (xlApp == null) 
            { 
                MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel"); 
                return; 
            } 
 
 
            Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks; 
            Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet); 
            Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1 
 
 
            string[] array = new string[myDGV.Columns.Count]; 
 
 
            //获取Visble =true 的列  
            foreach (DataGridViewColumn column in myDGV.Columns) 
            { 
                if (column.Visible == true) 
                { 
                    array[column.DisplayIndex] = column.HeaderText + '|' + column.Name; ; 
                } 
            } 
 
 
            int RowsCount = myDGV.Rows.Count; 
            int ColumnsCount = array.Length; 
            int mm = 1; 
            for (int i = 0; i < ColumnsCount; i++) 
            { 
                string[] str =new string[2]; 
                string ColumnName; 
                try 
                { 
                    str = array.GetValue(i).ToString().Split('|'); 
                    ColumnName = str[0]; 
                } 
                catch 
                { 
                    continue; 
                } 
                //导出列名   www.zzzyk.com
                worksheet.Cells[1, mm] = ColumnName; 
                //导出列内容  
                for (int m = 0; m < RowsCount; m++) 
                { 
                    try 
                    { 
                        worksheet.Cells[m + 2, mm] = myDGV.Rows[m].Cells[str[1]].FormattedValue.ToString(); 
                    } 
                    catch 
                    { } 
                } 
                //执行完一列 mm++  
                mm++; 
            } 
          

补充:软件开发 , C# ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,