网页中数据导出方法.net语言3.导出.doc .txt .xml格式的

//到出到Excel事件
    protected void ImageButton2_Click(object sender, ImageClickEventArgs e) powered by 25175.net
    {
        Scores score = new Scores();        //创建Scores对象      
        DataSet ds = score.QueryScore();     //调用QueryScore方法查询成绩并将查询结果放到DataSet数据集中
        DataTable DT = ds.Tables[0];
        //生成将要存放结果的Excel文件的名称
        string NewFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
        //转换为物理路径
        NewFileName = Server.MapPath("Temp/" + NewFileName);
        //根据模板正式生成该Excel文件
        File.Copy(Server.MapPath("../Module01.xls"), NewFileName, true);
        //建立指向该Excel文件的数据库连接
        string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + NewFileName + ";Extended Properties='Excel 8.0;'";
        OleDbConnection Conn = new OleDbConnection(strConn);
        //打开连接,为操作该文件做准备
        Conn.Open();
        OleDbCommand Cmd = new OleDbCommand("", Conn);

        foreach (DataRow DR in DT.Rows)
        {
            string XSqlString = "insert into [Sheet1$]";
            XSqlString += "([用户姓名],[试卷],[成绩],[考试时间]) values(";
            XSqlString += "'" + DR["UserName"] + "',";
            XSqlString += "'" + DR["PaperName"] + "',";
            XSqlString += "'" + DR["Score"] + "',";
            XSqlString += "'" + DR["ExamTime"] + "')";
            Cmd.CommandText = XSqlString;
            Cmd.ExecuteNonQuery();
        }

        //操作结束,关闭连接
        Conn.Close();
        //打开要下载的文件,并把该文件存放在FileStream中
        System.IO.FileStream Reader = System.IO.File.OpenRead(NewFileName);
        //文件传送的剩余字节数:初始值为文件的总大小
        long Length = Reader.Length;

        Response.Buffer = false;
        Response.AddHeader("Connection", "Keep-Alive");
        Response.ContentType = "application/octet-stream";
        Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode("学生成绩.xls"));
        Response.AddHeader("Content-Length", Length.ToString());

        byte[] Buffer = new Byte[10000];  //存放欲发送数据的缓冲区
        int ByteToRead;           //每次实际读取的字节数

        while (Length > 0)
        {
            //剩余字节数不为零,继续传送
            if (Response.IsClientConnected)
            {
                //客户端浏览器还打开着,继续传送
                ByteToRead = Reader.Read(Buffer, 0, 10000);     //往缓冲区读入数据
                Response.OutputStream.Write(Buffer, 0, ByteToRead); //把缓冲区的数据写入客户端浏览器
                Response.Flush();                  //立即写入客户端
                Length -= ByteToRead;                //剩余字节数减少
            }
            else
            {
                //客户端浏览器已经断开,阻止继续循环
                Length = -1;
            }
        }

        //关闭该文件
        Reader.Close();
        //删除该Excel文件
        File.Delete(NewFileName);
    }

 

 

asp.net里导出excel表方法汇总
 
1、由dataset生成

public void CreateExcel(DataSet ds,string typeid,string FileName) powered by 25175.net
{
HttpResponse resp;
resp = Page.Response;
resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);
string colHeaders= "", ls_item="";
int i=0;

//定义表对象与行对像,同时用DataSet对其值进行初始化
DataTable dt=ds.Tables[0];
DataRow[] myRow=dt.Select("");
// typeid=="1"时导出为EXCEL格式文件;typeid=="2"时导出为XML格式文件
if(typeid=="1")
{
//取得数据表各列标题,各标题之间以/t分割,最后一个列标题后加回车符
for(i=0;i colHeaders+=dt.Columns[i].Caption.ToString()+"/t";
colHeaders +=dt.Columns[i].Caption.ToString() +"/n";
//向HTTP输出流中写入取得的数据信息
resp.Write(colHeaders);
//逐行处理数据
foreach(DataRow row in myRow)
{
//在当前行中,逐列获得数据,数据之间以/t分割,结束时加回车符/n
for(i=0;i ls_item +=row[i].ToString() + "/t";
ls_item += row[i].ToString() +"/n";
//当前行数据写入HTTP输出流,并且置空ls_item以便下行数据
resp.Write(ls_item);
ls_item="";
}
}
else
{
if(typeid=="2")
{
//从DataSet中直接导出XML数据并且写到HTTP输出流中
resp.Write(ds.GetXml());
}
}
//写缓冲区中的数据到HTTP头文件中
resp.End();


}

 

2、使用微软的C++写的ACTIVEX控件:http://download.microsoft.com/download/OfficeXPDev/sample/1.0/WIN98MeXP/EN-US/Dsoframerctl.exe
3、由datagrid生成:

public void ToExcel(System.Web.UI.Control ctl)
{
HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=Excel.xls");
HttpContext.Current.Response.Charset ="UTF-8";
HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType ="application/ms-excel";//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword
ctl.Page.EnableViewState =false;
System.IO.StringWriter tw = new System.IO.StringWriter() ;
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
}

用法:ToExcel(datagrid1);


4、这个用dataview ,代码好长

public void OutputExcel(DataView dv,string str)
{
//
// TODO: 在此处添加构造函数逻辑
//
//dv为要输出到Excel的数据,str为标题名称
GC.Collect();
Application excel;// = new Application();
int rowIndex=4;
int colIndex=1;

_Workbook xBk;
_Worksheet xSt;

excel= new ApplicationClass();

xBk = excel.Workbooks.Add(true);

xSt = (_Worksheet)xBk.ActiveSheet;

//
//取得标题
//
foreach(DataColumn col in dv.Table.Columns)
{
colIndex++;
excel.Cells[4,colIndex] = col.ColumnName;
xSt.get_Range(excel.Cells[4,colIndex],excel.Cells[4,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;//设置标题格式为居中对齐
}

//
//取得表格中的数据
//
foreach(DataRowView row in dv)
{
rowIndex ++;
colIndex = 1;
foreach(DataColumn col in dv.Table.Columns)
{
colIndex ++;
if(col.DataType == System.Type.GetType("System.DateTime"))
{
excel.Cells[rowIndex,colIndex] = (Convert.ToDateTime(row[col.ColumnName].ToString())).ToString("yyyy-MM-dd");
xSt.get_Range(excel.Cells[rowIndex,colIndex],excel.Cells[rowIndex,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;//设置日期型的字段格式为居中对齐
}
else
if(col.DataType == System.Type.GetType("System.String"))
{
excel.Cells[rowIndex,colIndex] = "''"+row[col.ColumnName].ToString();
xSt.get_Range(excel.Cells[rowIndex,colIndex],excel.Cells[rowIndex,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;//设置字符型的字段格式为居中对齐
}
else
{
excel.Cells[rowIndex,colIndex] = row[col.ColumnName].ToString();
}
}
}
//
//加载一个合计行
//
int rowSum = rowIndex + 1;
int colSum = 2;
excel.Cells[rowSum,2] = "合计";
xSt.get_Range(excel.Cells[rowSum,2],excel.Cells[rowSum,2]).HorizontalAlignment = XlHAlign.xlHAlignCenter;
//
//设置选中的部分的颜色
//
xSt.get_Range(excel.Cells[rowSum,colSum],excel.Cells[rowSum,colIndex]).Select();
xSt.get_Range(excel.Cells[rowSum,colSum],excel.Cells[rowSum,colIndex]).Interior.ColorIndex = 19;//设置为浅黄色,共计有56种
//
//取得整个报表的标题
//
excel.Cells[2,2] = str;
//
//设置整个报表的标题格式
//
xSt.get_Range(excel.Cells[2,2],excel.Cells[2,2]).Font.Bold = true;
xSt.get_Range(excel.Cells[2,2],excel.Cells[2,2]).Font.Size = 22;
//
//设置报表表格为最适应宽度
//
xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,colIndex]).Select();
xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,colIndex]).Columns.AutoFit();
//
//设置整个报表的标题为跨列居中
//
xSt.get_Range(excel.Cells[2,2],excel.Cells[2,colIndex]).Select();
xSt.get_Range(excel.Cells[2,2],excel.Cells[2,colIndex]).HorizontalAlignment = XlHAlign.xlHAlignCenterAcrossSelection;
//
//绘制边框
//
xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,colIndex]).Borders.LineStyle = 1;
xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,2]).Borders[XlBordersIndex.xlEdgeLeft].Weight = XlBorderWeight.xlThick;//设置左边线加粗
xSt.get_Range(excel.Cells[4,2],excel.Cells[4,colIndex]).Borders[XlBordersIndex.xlEdgeTop].Weight = XlBorderWeight.xlThick;//设置上边线加粗
xSt.get_Range(excel.Cells[4,colIndex],excel.Cells[rowSum,colIndex]).Borders[XlBordersIndex.xlEdgeRight].Weight = XlBorderWeight.xlThick;//设置右边线加粗
xSt.get_Range(excel.Cells[rowSum,2],excel.Cells[rowSum,colIndex]).Borders[XlBordersIndex.xlEdgeBottom].Weight = XlBorderWeight.xlThick;//设置下边线加粗
//
//显示效果
//
excel.Visible=true;

//xSt.Export(Server.MapPath(".")+"//"+this.xlfile.Text+".xls",SheetExportActionEnum.ssExportActionNone,Microsoft.Office.Interop.OWC.SheetExportFormat.ssExportHTML);
xBk.SaveCopyAs(Server.MapPath(".")+"//"+this.xlfile.Text+".xls");

ds = null;
xBk.Close(false, null,null);

excel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xBk);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xSt);
xBk = null;
excel = null;
xSt = null;
GC.Collect();
string path = Server.MapPath(this.xlfile.Text+".xls");

System.IO.FileInfo file = new System.IO.FileInfo(path);
Response.Clear();
Response.Charset="GB2312";
Response.ContentEncoding=System.Text.Encoding.UTF8;
// 添加头信息,为"文件下载/另存为"对话框指定默认文件名
Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name));
// 添加头信息,指定文件大小,让浏览器能够显示下载进度
Response.AddHeader("Content-Length", file.Length.ToString());

// 指定返回的是一个不能被客户端读取的流,必须被下载
Response.ContentType = "application/ms-excel";

// 把文件流发送到客户端
Response.WriteFile(file.FullName);
// 停止页面的执行

Response.End();
}

 

 

.net将数据导出Word
1,首先要导入Com文件Microsoft Word 11.0 Object Library.
2.声明using System.Text.RegularExpressions; powered by 25175.net
-----------------------------------------------------------------
3.执行下面步骤
Object Nothing = System.Reflection.Missing.Value;
        //取得Word文件保存路径
        object filename = System.Web.HttpRuntime.AppDomainAppPath + "//XMLFiles//EduceWordFiles//" + this.Context.User.Identity.Name + ".doc";
        //创建一个名为WordApp的组件对象
        Word.Application WordApp = new Word.ApplicationClass();
        //创建一个名为WordDoc的文档对象
        Word.Document WordDoc = WordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
        //增加一表格
        //Word.Table table = WordDoc.Tables.Add(WordApp.Selection.Range, 1, 1, ref Nothing, ref Nothing);
        //在表格第一单元格中添加自定义的文字内容
        //table.Cell(1, 1).Range.Text = "在表格第一单元格中添加自定义的文字内容";
        //在文档空白地方添加文字内容
        //WordDoc.Paragraphs.Last.Range.Bold = 72;
        //WordApp.Visible = true;
        //WordDoc.Activate();


        #region 标题
        WordApp.Selection.Font.Size = 15;
        WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; // 居中
        WordApp.Selection.Font.Bold = 1;    // 黑体
        WordApp.Selection.TypeText(SaveShowInfo.Title);
        #endregion

        #region 时间和来源
        WordApp.Selection.TypeParagraph();
        WordApp.Selection.Font.Size = 10;
        WordApp.Selection.Font.Bold = 0;    // 取消黑体
        WordApp.Selection.TypeText("发布时间:" + SaveShowInfo.SaveTime + " 来源:" + SaveShowInfo.WebSiteName);
        #endregion

        #region 摘要
        WordApp.Selection.TypeParagraph();
        WordApp.Selection.TypeParagraph();
        WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft; // 居左
        WordApp.Selection.TypeText("摘要:");
        WordApp.Selection.TypeParagraph();
        //WordApp.Selection.ParagraphFormat.CharacterUnitFirstLineIndent = 2.0f;  //首行缩进2个字符
        WordApp.Selection.TypeText("    " + SaveShowInfo.Summary);
        #endregion

        #region 内容

        WordApp.Selection.TypeParagraph();
        WordApp.Selection.TypeParagraph();
        WordApp.Selection.TypeText("内容:");

        string strPageContent = SaveShowInfo.Content.ToString();
        //将一个<br>变成两个<br>
        //strPageContent = Regex.Replace(strPageContent, "(<br>[//s]*)+", "<br /><br />");
        //将所有标签去掉,只剩下/r/n
        strPageContent = Regex.Replace(strPageContent, @"<[^>]+/?>|</[^>]+>", "", RegexOptions.IgnoreCase);


        string[] strContents = strPageContent.Split(new string[] { "/r/n" }, StringSplitOptions.RemoveEmptyEntries);

        foreach (string strContent in strContents)
        {
            WordApp.Selection.TypeParagraph();
            WordApp.Selection.TypeText("    " + strContent);
        }

        #endregion

        #region 图片导出
       
        string[] strPictureUrls = SaveShowInfo.PictureUrl.Split(new string[] { "<br />" }, StringSplitOptions.RemoveEmptyEntries);
        if (strPictureUrls.Length != 0 && strPictureUrls[0] != "")
        {
            WordApp.Selection.TypeParagraph();
            WordApp.Selection.TypeParagraph();
            WordApp.Selection.TypeText("图片:");
            WordApp.Selection.TypeParagraph();
            WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; // 居中
            foreach (string strPictureUrl in strPictureUrls)
            {
                if (strPictureUrl.Length > 10)
                {
                    string strUrl = getPictureOnlyUrl(strPictureUrl);

                    WordApp.Selection.InlineShapes.AddPicture(strUrl, ref Nothing, ref Nothing, ref Nothing);
                    WordApp.Selection.TypeParagraph();

                }
            }
        }
        #endregion

        //WordDoc.Paragraphs.Last.Range.Text += SaveShowInfo.PictureUrl;

        //将WordDoc文档对象的内容保存为DOC文档
        WordDoc.SaveAs(ref filename, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
        //关闭WordDoc文档对象
        WordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
        //关闭WordApp组件对象
        WordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
        //返回结果
        //lblMsg.Text = "文档路径:<a href='/c://111.doc'>c://111.doc</a>(点击链接查看)<br>生成结果:成功!";

        //使导出文件清除特殊符号
        string outFileName = si.Title.Replace("/", " ");
        outFileName = outFileName.Replace("//", " ");
        outFileName = outFileName.Replace(":", " ");
        outFileName = outFileName.Replace("*", " ");
        outFileName = outFileName.Replace("?", " ");
        outFileName = outFileName.Replace("/"", " ");
        outFileName = outFileName.Replace("<", " ");
        outFileName = outFileName.Replace(">", " ");
        outFileName = outFileName.Replace("|", " ");
//这个是从服务器中下载文件,(请参考我另外一个文章)
//参考网址http://www.cnblogs.com/ghostljj/archive/2007/01/24/629293.html
ResponseFile(Page.Request, Page.Response, outFileName + ".doc"
            , System.Web.HttpRuntime.AppDomainAppPath + "//XMLFiles//EduceWordFiles//" + this.Context.User.Identity.Name + ".doc", 1024000);
//--------------------------------------------------------
3.如果是放在IIS中,现在是不能到出的,还要配置一下
方案一:在Web.config中添加
         <system.web>
               <identity impersonate="true" userName="管理员名" password="密码" />
         <system.web>
方案二:
         (1)在运行->dcomcnfg打开组件服务
         (2) 在 控制台根目录->组件服务->计算机->我的电脑->DCOM配置->Microsoft Word 文档->属性->安全
         (3)启动和激活权限->使用自定义->添加一个ASPnet用户,还有打开本地启动和本地激活
              访问权限->使用自定义->添加一个ASPnet用户,还有打开本地访问和远程访问

 

 

 

using System;
using System.Data;
using System.Drawing;
using System.Data.SqlClient;
using Excel; powered by 25175.net
using Word;
using System.IO;
namespace Common
{
 /// <summary>
 /// 把数据导入到.doc、.txt、.xls文件中
 /// </summary>
 public class Export
 {
  private const string DATAWORDPATH = @"C:/folder/doc/datadoc/";
  private const string IMAGEWORDPATH = @"C:/folder/doc/imagedoc/";
  private const string IMAGEPATH = @"C:/folder/image/";
  private const string EXCELPATH = @"C:/folder/excel/";
  private const string TXTPATH = @"C:/folder/txt/";
  private const string IMAGEPOSTFIX = ".bmp";
  private const string WORDPOSTFIX = ".doc";
  private const string EXCELPOSTFIX = ".xls";
  private const string TXTPOSTFIX = ".txt";
  private const int DATADISTANCE = 5;
  private const int TABDISTANCE = 8;
 
  public Export()
  {
   //
   // TODO: 在此处添加构造函数逻辑
   //
  }

  /// <summary>
  /// 获得数据集Dataset--------------------------------用于调试
  /// </summary>
  /// <returns>Dataset</returns>
  public DataSet GetData()
  {
   try
   {
    string sConnectionString;
    sConnectionString = "workstation id=GUOFU;packet size=4096;user id=sa;data source=GUOFU;persist security info=True;initial catalog=YC;password=sc";
    SqlConnection objConn = new SqlConnection(sConnectionString);
    objConn.Open();                                           
    SqlDataAdapter daPoint = new SqlDataAdapter("Select * From Point", objConn);
    DataSet dsYC = new DataSet("YC");
    daPoint.FillSchema(dsYC,SchemaType.Mapped, "Point");
    daPoint.Fill(dsYC,"Point");
    daPoint = new SqlDataAdapter("Select * From Employee", objConn);
    daPoint.FillSchema(dsYC,SchemaType.Mapped, "Employee");
    daPoint.Fill(dsYC,"Employee");
    return dsYC;
   }
   catch(Exception ex)
   {
    throw new Exception(ex.Message);
   }

  }

  /// <summary>
  /// 把数据文件导入到.xls文件
  /// </summary>
  /// <param name="ds"></param>
  public void ExportToExcel(DataSet ds)
  {

   if(ds.Tables.Count!=0)
   {
    //生成.xls文件完整路径名
    string tempFileName = GetTempFileName();
    object filename = EXCELPATH+tempFileName+EXCELPOSTFIX;
    object Nothing = System.Reflection.Missing.Value;
   
    //创建excel文件,文件名用系统时间生成精确到毫秒
    Excel.Application myExcel = new Excel.ApplicationClass();
    myExcel.Application.Workbooks.Add(Nothing);

    try
    {
     //把Dataset中的数据插入excel文件中
     int totalCount = 0;
     for(int k =0;k<ds.Tables.Count;k++)
     {
      int row = ds.Tables[k].Rows.Count;
      int column = ds.Tables[k].Columns.Count;
   
      for(int i = 0;i<column;i++)
      {
       myExcel.Cells[totalCount+2,1+i] = ds.Tables[k].Columns[i].ColumnName;
      }

      for(int i = 0;i<row;i++)
      {
       for(int j =0;j<column;j++)
       {
        myExcel.Cells[totalCount+3+i,1+j] = "" + ds.Tables[k].Rows[i][j].ToString();
       }
      }
      totalCount = totalCount + row +4;
     }

     try
     {
      //保存excel文件到指定的目录下,文件名用系统时间生成精确到毫秒
      myExcel.ActiveWorkbook._SaveAs(filename,Nothing,Nothing,Nothing,Nothing,Nothing,XlSaveAsAccessMode.xlExclusive,Nothing,Nothing,Nothing,Nothing);
     }
     catch
     {
      System.Windows.Forms.MessageBox.Show("系统找不到指定目录下的文件:  "+EXCELPATH+tempFileName+EXCELPOSTFIX);
      return;
     }
     //让生成的excel文件可见
     myExcel.Visible = true;
    }
    catch(Exception e)
    {
     System.Windows.Forms.MessageBox.Show("向excel文件中写入数据出错:  " + e.Message);
    }
   }
   else
   {
    System.Windows.Forms.MessageBox.Show("No Data");
   }
  }


  /// <summary>
  /// 把数据导入到.doc文件
  /// </summary>
  /// <param name="ds"></param>
  public void ExportToWord(DataSet ds)
  {
   if(ds.Tables.Count!=0)
   {  
    string tempFileName = null;
    object filename = null;
   
    object tableBehavior = Word.WdDefaultTableBehavior.wdWord9TableBehavior;
    object autoFitBehavior = Word.WdAutoFitBehavior.wdAutoFitFixed;

    object unit = Word.WdUnits.wdStory;
    object extend = System.Reflection.Missing.Value;
    object breakType = (int)Word.WdBreakType.wdSectionBreakNextPage;

    object count = 1;
    object character = Word.WdUnits.wdCharacter;

    object Nothing =  System.Reflection.Missing.Value;
   
    try
    {
     tempFileName = GetTempFileName();

     //生成.doc文件完整路径名
     filename = DATAWORDPATH+tempFileName+WORDPOSTFIX;
    
     //创建一个word文件,文件名用系统时间生成精确到毫秒
     Word.Application myWord= new Word.ApplicationClass();
     Word._Document myDoc = new Word.DocumentClass();
     myDoc = myWord.Documents.Add(ref Nothing,ref Nothing,ref Nothing,ref Nothing);
     myDoc.Activate();

     //向把dataset中的表插入到word的文件中
   
     for(int totalTable = 0;totalTable<ds.Tables.Count;totalTable++)
     {
      myWord.Application.Selection.TypeText(ds.Tables[totalTable].TableName+"表的数据如下");
      myWord.Application.Selection.TypeParagraph();    
      myWord.Application.Selection.TypeParagraph();
      Word.Range para = myWord.Application.Selection.Range;
      myDoc.Tables.Add(para,ds.Tables[totalTable].Rows.Count+1,ds.Tables[totalTable].Columns.Count,ref tableBehavior,ref autoFitBehavior);
      for(int column = 0; column<ds.Tables[totalTable].Columns.Count;column++)
      {
       myDoc.Tables.Item(totalTable+1).Cell(1,column+1).Range.InsertBefore(ds.Tables[0].Columns[column].ColumnName.Trim());
      }   
      for(int row = 0;row<ds.Tables[totalTable].Rows.Count;row++)
      {
       for(int column = 0;column<ds.Tables[totalTable].Columns.Count;column++)
       {
        myDoc.Tables.Item(totalTable+1).Cell(row+2,column+1).Range.InsertBefore(ds.Tables[totalTable].Rows[row][column].ToString().Trim());
       }
      }
      myWord.Application.Selection.EndKey(ref unit,ref extend);
      myWord.Application.Selection.TypeParagraph();
      myWord.Application.Selection.TypeParagraph();
      myWord.Application.Selection.InsertBreak(ref breakType);   
     }
     myWord.Application.Selection.TypeBackspace();
     myWord.Application.Selection.Delete(ref character,ref count);
     myWord.Application.Selection.HomeKey(ref unit,ref extend);
   
     //保存word文件到指定的目录下
     try
     {
      myDoc.SaveAs(ref filename,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing);
      myWord.Visible = true;
     }
     catch
     {
      System.Windows.Forms.MessageBox.Show("系统找不到指定目录下的文件:  "+DATAWORDPATH+tempFileName+WORDPOSTFIX);
      return;
     }
     //让生成的excel文件可见
     myWord.Visible = true;
    }
    catch(Exception ex)
    {
     System.Windows.Forms.MessageBox.Show("向word文件中写入数据出错:  " + ex.Message);
    }
   }
   else
   {
    System.Windows.Forms.MessageBox.Show("No Data");
   }
  }
  /// <summary>
  /// 把图片文件导入到.doc文件
  /// </summary>
  /// <param name="bp"></param>
  public void ExportToWord(Bitmap bp)
  {
   string tempFileName = null;
   string bmpPath = null;
   object filename = null;
   object Nothing = null;
   tempFileName = GetTempFileName();

 
   //生成.bmp文件完整路径名
   bmpPath = IMAGEPATH+tempFileName+IMAGEPOSTFIX;

   //生成.doc文件完整路径名
   filename = IMAGEWORDPATH+tempFileName+WORDPOSTFIX;
   Nothing = System.Reflection.Missing.Value;
 
   //创建一个word文件,文件名用系统时间生成精确到毫秒
   Word.Application myWord= new Word.ApplicationClass();
   Word._Document myDoc = new Word.DocumentClass();
   myDoc = myWord.Documents.Add(ref Nothing,ref Nothing,ref Nothing,ref Nothing); 

   try
   {
    //把bitmap对象保存到系统所生成文件完整路径中
    bp.Save(bmpPath);
   }
   catch
   {
    System.Windows.Forms.MessageBox.Show("系统找不到指定目录下的文件:  "+bmpPath);
    return;
   }
 
   try
   {
    //往word文件中插入图片
    myDoc.InlineShapes.AddPicture(bmpPath,ref Nothing,ref Nothing,ref Nothing);
   }
   catch
   {
    System.Windows.Forms.MessageBox.Show("系统找不到指定目录下的文件:  "+bmpPath);
    return;
   }
 
   try
   {
    //保存word文件到指定的目录下
    myDoc.SaveAs(ref filename,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing);
   }
   catch
   {
    System.Windows.Forms.MessageBox.Show("系统找不到指定目录下的文件:  "+IMAGEWORDPATH+tempFileName+WORDPOSTFIX);
    return;
   }

   //让生成的word文件可见
   myWord.Visible = true;
  }


  /// <summary>
  /// 把数据文件导入到.txt文件
  /// </summary>
  /// <param name="ds"></param>
  public void ExportToTxt(DataSet ds)
  {

   if(ds.Tables.Count!=0)
   {
    string tempFileName = null;
    tempFileName = GetTempFileName();

 
    //创建一个.txt文件,文件名用系统时间生成精确到毫秒
    FileInfo file = new FileInfo(TXTPATH+tempFileName+TXTPOSTFIX);
    StreamWriter textFile = null;
    try
    {
     textFile = file.CreateText();
    }
    catch
    {
     System.Windows.Forms.MessageBox.Show("系统找不到指定目录下的文件:  "+TXTPATH+tempFileName+TXTPOSTFIX);
     return;
    }

    //把Dataset中的数据写入.txt文件中
    for(int totaltable = 0;totaltable<ds.Tables.Count;totaltable++)
    {
     //统计dataset中当前表的行数
     int row = ds.Tables[totaltable].Rows.Count;

     //统计dataset中当前表的列数
     int column = ds.Tables[totaltable].Columns.Count;

     //用于统计当前表中每列记录中字符数最长的字符串的长度之和
     int totalLength = 0;

     //用于统计标题的长度(dataset中的表名的length+"表的数据如下"的length)
     int titleLength = 0;

     //统计每列记录中字符数最长的字符串的长度
     int[] columnLength = new int[column];
     for(int i = 0;i<column;i++)
     {
      columnLength[i] = ds.Tables[totaltable].Columns[i].ColumnName.ToString().Length;
     }
     for(int i = 0;i<row;i++)
     {
      for(int j = 0;j<column;j++)
      {
       if(ds.Tables[totaltable].Rows[i][j].ToString().Length>columnLength[j])
       {
        columnLength[j]=ds.Tables[totaltable].Rows[i][j].ToString().Length;
       }
      }
     }


     //统计当前表中每列记录中字符数最长的字符串的长度之和
     for(int i = 0;i<column;i++)
     {
      totalLength = totalLength+columnLength[i]+DATADISTANCE;
     }
     totalLength = totalLength+2*TABDISTANCE-DATADISTANCE;

     //统计标题的长度(dataset中的当前表名的length+"表的数据如下"的length)
     titleLength = ds.Tables[totaltable].TableName.ToString().Length+"表的数据如下".Length*2;

     //把标题写入.txt文件中
     for(int i = 0;i<(int)((totalLength-titleLength)/2);i++)
     {
      textFile.Write( );
     }
     textFile.Write(ds.Tables[totaltable].TableName+"表的数据如下");
     textFile.WriteLine();
     for(int i = 0;i<totalLength;i++)
     {
      textFile.Write(*);
     }
     textFile.WriteLine();
     textFile.Write("/t");

     //把dataset中当前表的字段名写入.txt文件中
     for(int i = 0;i<column;i++)
     {
      textFile.Write(ds.Tables[totaltable].Columns[i].ColumnName.ToString());
      for(int k = 0;k<columnLength[i]-ds.Tables[totaltable].Columns[i].ColumnName.ToString().Length+DATADISTANCE;k++)
      {
       textFile.Write( );
      }
     }
     textFile.WriteLine();
     for(int i = 0;i<totalLength;i++)
     {
      textFile.Write(-);
     }
     textFile.WriteLine();
     textFile.Write("/t");

     //把dataset中当前表的数据写入.txt文件中
     for(int i = 0;i<row;i++)
     {
      for(int j = 0;j<column;j++)
      {
       textFile.Write(ds.Tables[totaltable].Rows[i][j].ToString());
       for(int k = 0;k<columnLength[j]-ds.Tables[totaltable].Rows[i][j].ToString().Length+DATADISTANCE;k++)
       {
        textFile.Write( );
       }
      }
      textFile.WriteLine();
      textFile.Write("/t");
     }
     textFile.WriteLine();
     for(int i = 0;i<totalLength;i++)
     {
      textFile.Write(-);
     }
     textFile.WriteLine();
     textFile.WriteLine();
     textFile.WriteLine();
    }

    //关闭当前的StreamWriter流
    textFile.Close();
    System.Windows.Forms.MessageBox.Show("数据文件已保存到"+"   "+file.FullName);                
   }
   else
   {
    System.Windows.Forms.MessageBox.Show("No Data");
   }
  }

  public string GetTempFileName()
  {
   return DateTime.Now.ToString("yyyyMMddhhmmssfff");
  }
 }
}

补充:使用以上方法必须对dcom进行配置,给用户使用office的权限。
具体配置方法如下:
1:在服务器上安装office的Excel软件.
2:在"开始"->"运行"中输入dcomcnfg.exe启动"组件服务"
3:依次双击"组件服务"->"计算机"->"我的电脑"->"DCOM配置"
4:在"DCOM配置"中找到"Microsoft Excel 应用程序",在它上面点击右键,然后点击"属性",弹出"Microsoft Excel 应用程序属性"对话框
5:点击"标识"标签,选择"交互式用户"
6:点击"安全"标签,在"启动和激活权限"上点击"自定义",然后点击对应的"编辑"按钮,在弹出的"安全性"对话框中填加一个"netWORK SERVICE"用户(注意要选择本计算机名),并给它赋予"本地启动"和"本地激活"权限.
7:依然是"安全"标签,在"访问权限"上点击"自定义",然后点击"编辑",在弹出的"安全性"对话框中也填加一个"netWORK SERVICE"用户,然后赋予"本地访问"权限.
这样,我们便配置好了相应的Excel的DCOM权限.
注意:我是在WIN2003上配置的,在2000上,是配置ASPnet用户

若不进行配置会出现错误
检索 COM 类工厂中 CLSID 为 {00024500-0000-0000-C000-000000000046} 的组件时失败,原因是出现以下错误: 80070005。
原因是用户没有使用Excel的权限。
导出到word同样要配置使用word的权限。 
继续补充: 导出到txt我用了上面的方法有问题,
try
{
textFile = file.CreateText();
}
catch
{
System.Windows.Forms.MessageBox.Show("系统找不到指定目录下的文件: "+TXTPATH+tempFileName+TXTPOSTFIX);
return;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值