想做个通用的导出excel的类,是不是写几个静态函数就行了呀?
----------------------------------------------------------
我看过别人写的源码,都是在窗体中操作,导出excel,
可是我想做一个通过的导出电子表格的功能,
我想,写个类,然后将导出excel的函数设定为静态,这样可行吗?因为我觉得不用实例化吧。因为直接用里面的函数,
这种情况,是不是用静态函数更好些,这个类也不用实例化,拿来就用?

解决方案 »

  1.   

    /// <summary>
        /// 导入导出Excel
        /// </summary>
        public class ExcelClass
        {
            /// <summary>
            /// 导出到Excel
            /// </summary>
            /// <param name="fileName">文件路径</param>
            /// <param name="myDGV">DataGridView</param>
            static public 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;
                if (saveDialog.ShowDialog() != DialogResult.OK) return;
                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             //写入标题
                for (int i = 1; i < myDGV.ColumnCount; i++)
                {
                    worksheet.Cells[1, i] = myDGV.Columns[i].HeaderText;
                }
                //写入数值
                for (int r = 0; r < myDGV.Rows.Count; r++)
                {
                    for (int i = 1; i < myDGV.ColumnCount; i++)
                    {
                        worksheet.Cells[r + 2, i] = myDGV.Rows[r].Cells[i].Value;
                    }
                    System.Windows.Forms.Application.DoEvents();
                }
                worksheet.Columns.EntireColumn.AutoFit();//列宽自适应
                if (saveFileName != "")
                {
                    try
                    {
                        workbook.Saved = true;
                        workbook.SaveCopyAs(saveFileName);
                        fileSaved = true;
                    }
                    catch (Exception ex)
                    {
                        fileSaved = false;
                        MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
                    }
                    //MessageBox.Show(fileName + "保存成功", "提示", MessageBoxButtons.OK);
                }
                else
                {
                    fileSaved = false;
                }
                xlApp.Quit();
                GC.Collect();//强行销毁 
                if (fileSaved && System.IO.File.Exists(saveFileName)) System.Diagnostics.Process.Start(saveFileName); //打开EXCEL
            }
            /// <summary>
            /// 从Excel导入
            /// </summary>
            /// <param name="filePath">文件路径</param>
            /// <param name="ds">Excel数据保存到数据集</param>
            static public void EcxelToDataGridView(string filePath, ref DataSet ds)
            {
                //根据路径打开一个Excel文件并将数据填充到DataSet中
                string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = " + filePath + ";Extended Properties ='Excel 8.0;HDR=YES;IMEX=1'";//导入时包含Excel中的第一行数据,并且将数字和字符混合的单元格视为文本进行导入
                OleDbConnection conn1 = new OleDbConnection(strConn);
                conn1.Open();
                string strExcel = "";
                OleDbDataAdapter myCommand1 = null;
                strExcel = "select  * from   [sheet1$]";
                myCommand1 = new OleDbDataAdapter(strExcel, strConn);
                //ds.Enforc/eConstraints = false;
                myCommand1.Fill(ds);
                conn1.Close();
            }    }
      

  2.   

    可以这样做,不过你要传递很多参数。
    我觉得要灵活的话还是写一个类比较好。推荐你用Excel的XML来实现,这样可以避免Excel高版本打不开文件的情况。
      

  3.   


    我这样做就是写一个类呀,不然函数放在哪里呀。
    另外,你说的用xml,是什么意思,会不会导出来后,低版本打不开呀。
      

  4.   


    2003和2007都没问题,再低的版本估计就没用的了。以前用GridView导出Excel,在2007中打开就会出错。后来我都把程序改了。
      

  5.   

    2003和2007都没问题,再低的版本估计就没用的了。以前用GridView导出Excel,在2007中打开就会出错。后来我都把程序改了。
    ------------------------------
    如果导出 csv 格式,就能保证所有excel版本都能打开了,
    当然,格式就无法设置了。
      

  6.   

    这几天我做了一个,感觉直接导出html到excel比较方便,可以借鉴一下哦
      

  7.   

    // JScript 文件
    function replaceHtml(replacedStr,repStr,endStr){   
        var replacedStrF = "";   
        var replacedStrB = "";   
        var repStrIndex = replacedStr.indexOf(repStr);   
        while(repStrIndex != -1){   
            replacedStrF = replacedStr.substring(0,repStrIndex);   
            replacedStrB = replacedStr.substring(repStrIndex,replacedStr.length);   
            replacedStrB = replacedStrB.substring(replacedStrB.indexOf(endStr)+1,replacedStrB.length);   
            replacedStr = replacedStrF + replacedStrB;   
            repStrIndex = replacedStr.indexOf(repStr);   
        }   
        return replacedStr;   
    }   
    //elTalbeOut 这个为导出内容的外层表格,主要是设置border之类的样式,elDiv则是整个导出的html部分   
    function htmlToExcel(elTableOut,elDiv){   
        try{   
            //设置导出前的数据,为导出后返回格式而设置   
            var elDivStrBak = elDiv.innerHTML;   
            //设置table的border=1,这样到excel中就有表格线 ps:感谢双面提醒   
            elTableOut.border=1;   
            //过滤elDiv内容   
            var elDivStr = elDiv.innerHTML;   
            elDivStr = replaceHtml(elDivStr,"<A",">");   
            elDivStr = replaceHtml(elDivStr,"</A",">");   
            elDiv.innerHTML=elDivStr;      
               
            var oRangeRef = document.body.createTextRange();   
            oRangeRef.moveToElementText( elDiv );   
            oRangeRef.execCommand("Copy");   
               
            //返回格式变换以前的内容   
            elDiv.innerHTML = elDivStrBak;   
            //内容数据可能很大,所以赋空   
            elDivStrBak = "";   
            elDivStr = "";   
               
            var oXL = new ActiveXObject("Excel.Application")   
            var oWB = oXL.Workbooks.Add ;   
            var oSheet = oWB.ActiveSheet ;   
            oSheet.Paste();   
            oSheet.Cells.NumberFormatLocal = "@";   
            oSheet.Columns("D:D").Select   
            oXL.Selection.ColumnWidth = 20  
            oXL.Visible = true;        
            oSheet = null;   
            oWB = null;   
            appExcel = null;   
        }catch(e){   
            alert(e.description)   
        }   
    }   
    在页面上引用js
    按钮:<INPUT type="button" value="导出Excel" id="dcExcel" onClick="htmlToExcel(document.getElementById('elTableOut'),document.getElementById('elDiv'));">
    <div id="elDiv">
    <table id="elTableOut">
    内容。。
    </table>
    </div>