以下这段代码是在网上找到的,但红色部分会报错:无效识别的转义序列,常量中有换行符,,,麻烦大家帮我看看。谢谢代码:
        //// <summary>
        /// 将DataGridView中的数据导出到Excel中,并加载显示出来(加载模板)
        /// 仅用于导出已定义好模版的Excel导出,主要如“旬报表”,“月报表”等
        /// 请注意:模板应放在应程序的PrintTemplate目录下        /// </summary>
        /// <param name="ModelName">模版的名称</param>
        /// <param name="Date">打印日期</param>
        /// <param name="dgv">要进行导出的DataGridView</param>
        public void ExportToExcelByModel(string ModelName, string Date, DataGridView dgv)
        {
            Excel.Application m_objExcel = null;
            Excel._Workbook m_objBook = null;
            Excel.Sheets m_objSheets = null;
            Excel._Worksheet m_objSheet = null;
            object m_objOpt = System.Reflection.Missing.Value;
            try
            {
                m_objExcel = new Excel.Application();
                string path = System.Windows.Forms.Application.StartupPath.ToString().Replace("\bin\Debug", "") + "\PrintTemplate\";                path = path + ModelName;
                m_objBook = m_objExcel.Workbooks.Open(path, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt);                m_objSheets = (Excel.Sheets)m_objBook.Worksheets;
                m_objSheet = (Excel._Worksheet)(m_objSheets.get_Item(1));                //填充日期
                m_objExcel.Cells[2, 1] = Date.ToString();                //当前操作列的索引
                int currentcolumnindex = 1;
                //当前操作行的索引
                int currentrowindex = 4;
                for (int i = 0; i < dgv.Rows.Count; i++)   //循环填充数据
                {
                    currentcolumnindex = 1;
                    currentrowindex = 4 + i;
                    for (int j = 0; j < dgv.Columns.Count; j++)
                    {
                        if (dgv.Columns[j].Visible == true)
                        {
                            if (dgv[j, i].Value != null) //如果单元格内容不为空
                            {
                                m_objExcel.Cells[currentrowindex, currentcolumnindex] = dgv[j, i].Value.ToString();
                            }
                            m_objExcel.get_Range(m_objExcel.Cells[currentrowindex, currentcolumnindex], m_objExcel.Cells[currentrowindex, currentcolumnindex]).Cells.Borders.LineStyle = 1; //设置边框
                            currentcolumnindex++;
                        }
                    }
                }
                m_objExcel.DisplayAlerts = false;
                m_objExcel.Visible = true;
                System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objBook);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objExcel);
            }
            catch
            {
                MessageBox.Show("信息导出失败,请确认你的机子上装有Microsoft Office Excel 2003并且模版未被删除!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                GC.Collect();
            }
        }

解决方案 »

  1.   

    string path = System.Windows.Forms.Application.StartupPath.ToString().Replace("\\bin\\Debug", "") + "\\PrintTemplate\\"; 
      

  2.   

    这一句又报错:错误  “Open”方法没有采用“15”个参数的重载m_objBook = m_objExcel.Workbooks.Open(path, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt);
      

  3.   

    用这段代可以实现你要的功能.
      //DataTable中的数据导出Excel文件
        /// <summary>
        /// 将DataTable中的数据导出到指定的Excel文件中
        /// </summary>
        /// <param name="page">Web页面对象</param>
        /// <param name="tab">包含被导出数据的DataTable对象</param>
        /// <param name="FileName">Excel文件的名称</param>
        public static void Export(System.Web.UI.Page page,System.Data.DataTable tab,string FileName)
        {
          System.Web.HttpResponse httpResponse = page.Response;
          System.Web.UI.WebControls.DataGrid dataGrid=new System.Web.UI.WebControls.DataGrid();
          dataGrid.DataSource=tab.DefaultView;
          dataGrid.AllowPaging = false;
          dataGrid.HeaderStyle.ForeColor = Color.White;
          dataGrid.HeaderStyle.BackColor = Color.FromName("#aaaadd");
          dataGrid.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
          dataGrid.HeaderStyle.Font.Bold = true;
          dataGrid.DataBind();
          httpResponse.AppendHeader("Content-Disposition","attachment;filename="+HttpUtility.UrlEncode(FileName,System.Text.Encoding.UTF8)); //filename="*.xls";
          httpResponse.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
          httpResponse.ContentType ="application/ms-excel";
          System.IO.StringWriter  tw = new System.IO.StringWriter() ;
          System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw);
          dataGrid.RenderControl(hw);
       
          string filePath = page.Server.MapPath(" .")+"\\Files\\" +FileName;
          if( !Directory.Exists(Path.GetDirectoryName(filePath)))
            Directory.CreateDirectory(Path.GetDirectoryName(filePath)) ;      System.IO.StreamWriter sw = System.IO.File.CreateText(filePath);
          sw.Write(tw.ToString());
          sw.Close();      DownFile(httpResponse,FileName,filePath);
      
          httpResponse.End();
        }
        private static bool DownFile(System.Web.HttpResponse Response,string fileName,string fullPath)
        {
          try
          {
            Response.ContentType = "application/octet-stream";
        
            Response.AppendHeader("Content-Disposition","attachment;filename=" + 
              HttpUtility.UrlEncode(fileName,System.Text.Encoding.UTF8) + ";charset=GB2312"); 
            System.IO.FileStream fs= System.IO.File.OpenRead(fullPath);
            long fLen=fs.Length;
            int size=102400;//每100K同时下载数据 
            byte[] readData = new byte[size];//指定缓冲区的大小 
            if(size>fLen)size=Convert.ToInt32(fLen);
            long fPos=0;
            bool isEnd=false;
            while (!isEnd) 
            { 
              if((fPos+size)>fLen)
              {
                size=Convert.ToInt32(fLen-fPos);
                readData = new byte[size];
                isEnd=true;
              }
              fs.Read(readData, 0, size);//读入一个压缩块 
              Response.BinaryWrite(readData);
              fPos+=size;
            } 
            fs.Close(); 
            System.IO.File.Delete(fullPath);
            return true;
          }
          catch
          {
            return false;
          }
        }
      

  4.   

    其实你可以考虑用Talbe 前边加Excel文件头 来生成Excel 这样速度快很多很多,,
    只不过严格意义上说他是伪Excel而已 但正常使用没什么问题
    如果你的表格某单元格需要变颜色而且量很大 你就头疼了,,那速度根本无法忍受
      

  5.   

    检查引用COM组件版本
     path = System.Windows.Forms.Application.StartupPath.ToString().Replace(@"\bin\Debug", "") + @"\PrintTemplate\";