代码如下:

         int intDataCount = myData.Tables[0].Rows.Count;

       Microsoft.Office.Interop.Excel.Application app = null;
Microsoft.Office.Interop.Excel.Workbook workbook = null;
Microsoft.Office.Interop.Excel.Worksheet sheet = null;
object missing = System.Reflection.Missing.Value; //     表示 System.Reflection.Missing 类的唯一实例。
string strPath = string.Empty;
string strFileName = string.Empty;
try
{
app = new Microsoft.Office.Interop.Excel.Application();
app.Visible = false; // 不显示,仅后台生成
workbook = app.Workbooks.Add(true); // 如果打开已存在文件,这里用Open,保存使用Save
// 添加sheet的方法
workbook.Worksheets.Add(missing, missing, missing, missing);
// 修改sheet名的方法,注意sheet的下标从1开始
sheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[];
sheet.Name = "new sheet name"; //想要将sheet的名称改为Sheet1,则需改
// 添加sheet的方法
// 注销 workbook.Worksheets.Add(missing, missing, missing, missing);
// 中间不变
//sheet.Name = "Sheet1"; //添加标题
app.Cells[, ] = strTitle;
app.Cells[, ] = "项目名称:" + myData.Tables[].Rows[][“columnName”].ToString();
//合并单元格
sheet.get_Range(sheet.Cells[, ], sheet.Cells[, ]).MergeCells = true;
sheet.get_Range(sheet.Cells[, ], sheet.Cells[, ]).MergeCells = true;
//居中对齐
sheet.get_Range(sheet.Cells[, ], sheet.Cells[, ]).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
//设置字体
sheet.get_Range(sheet.Cells[, ], sheet.Cells[, ]).Font.Size = ;
sheet.get_Range(sheet.Cells[, ], sheet.Cells[, ]).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
// 设置字体和大小
//range = sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[rowCount, columnCount]);
//range.Font.Name = “Arial”;
//range.Font.Size = 10; // 设置单元格的wrap text属性
sheet.get_Range(sheet.Cells[, ], sheet.Cells[intDataCount + , ]).WrapText = true;
// 设置单元格的数据格式为文本格式
sheet.get_Range(sheet.Cells[, ], sheet.Cells[intDataCount + , ]).NumberFormat = "@";
//设置自动调整列宽
sheet.get_Range(sheet.Cells[, ], sheet.Cells[intDataCount + , ]).EntireColumn.AutoFit();
          //sheet.Range[sheet.Cells[1, 1], sheet.Cells[intDataCount + 1, 13]].EntireColumn.ColumnWidth = 20;

          sheet.Range[sheet.Cells[1, 1], sheet.Cells[intDataCount + 1, 13]].WrapText = false;
          sheet.Range[sheet.Cells[1, 1], sheet.Cells[intDataCount + 1, 13]].NumberFormat = "@";
          sheet.Range[sheet.Cells[1, 1], sheet.Cells[intDataCount + 1, 13]].EntireRow.AutoFit();
          sheet.Range[sheet.Cells[1, 1], sheet.Cells[intDataCount + 1, 13]].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;



                Microsoft.Office.Interop.Excel.Range range;
Array arr = Array.CreateInstance(typeof(object), intDataCount + , );
// 不断的调用下面的的函数填充array中的内容
// 行,列均从0开始 arr.SetValue("列名1", , );
arr.SetValue("列名2", , );
arr.SetValue("列名3", , );
arr.SetValue("列名4", , );
arr.SetValue("列名5", , );
arr.SetValue("列名6", , );
int i = ;
foreach (DataRow row in myData.Tables[].Rows)
{
arr.SetValue(row["columnName1"], i, );
arr.SetValue(row["columnName2"], i, );
arr.SetValue(row["columnName3"], i, );
arr.SetValue(row["columnName4"], i, );
arr.SetValue(row["columnName5"], i, );
arr.SetValue(row["columnName6"], i, );
i++;
} // 设置array数据,注意选择的行数和列数要与array行数和列数对应
//sheet.get_Range(sheet.Cells[, ], sheet.Cells[intDataCount + , ]).Value2 = arr;
         sheet.Range[sheet.Cells[1, 1], sheet.Cells[intDataCount + 1, 13]].Value2 = arr;
// 这里给sheet填充内容部分略
// 如果文件已经存在又不想让“是否替换”的提示窗体显示出来,需要先调用File.Delete来删除文件
strFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";
strPath = Server.MapPath("~/upload");
workbook.SaveAs(strPath + "\\" + strFileName, missing, missing, missing, missing, missing,
Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, missing, missing,
missing, missing, missing);

          HylExcel.NavigateUrl = string.Format(@"{0}/{1}/{2}", PageBase.UrlBase, PageBase.UploadDir, strFileName);
          HylExcel.Text = string.Format("<span style='color:red;font-weight:bold;'>点这里下载Excel文件{0}</span>", strFileName);


                workbook.Close(false, missing, missing);
app.Quit();
workbook = null;
app = null;
GC.Collect(); //FileInfo fi = new FileInfo(strPath + "\\" + strFileName);//excelFile为文件在服务器上的地址
//HttpResponse contextResponse = HttpContext.Current.Response;
//contextResponse.Clear();
// contextResponse.Buffer = true;
//contextResponse.Charset = "GB2312"; //设置了类型为中文防止乱码的出现
// contextResponse.AppendHeader("Content-Disposition", String.Format("attachment;filename={0}", fi.Name)); //定义输出文件和文件名
///contextResponse.AppendHeader("Content-Length", fi.Length.ToString());
//contextResponse.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
//contextResponse.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。 //contextResponse.WriteFile(fi.FullName);
// contextResponse.Flush();
//fi.Delete();
}
catch (Exception ex)
{
if (app != null)
{
app.Quit();
app = null;
GC.Collect();
}
}

C#如何表格型数据导出到Excel?的更多相关文章

  1. html实现类似excel的复杂表格,及导出到excel

    1. excellentexport.js https://github.com/jmaister/excellentexport/tree/2.0.3 2.fiddle example  https ...

  2. 纯JS 将table表格导出到excel

    html <div > <button type="button" onclick="getXlsFromTbl('tableExcel','myDiv ...

  3. asp.net将内容导出到Excel,Table表格数据(html)导出EXCEL

    代码: /// <summary> /// HTML Table表格数据(html)导出EXCEL /// </summary> /// <param name=&quo ...

  4. 将HTML表格导出到EXCEL,兼容Firefox,支持中文

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  5. 使用JavaScript把页面上的表格导出为Excel文件

    如果在页面上展示了一个数据表格,而用户想把这个表格导出为Excel文件,那么在要求不高的情况下,可以不通过服务器生成表格,而是直接利用JavaScript的Blob和Object URL特性将表格导出 ...

  6. Python实现数据库一键导出为Excel表格

    依赖 Python2711 xlwt MySQLdb 数据库相关 连接 获取字段信息 获取数据 Excel基础 workbook sheet 案例 封装 封装之后 测试结果 总结 数据库数据导出为ex ...

  7. 网站开发进阶(三十一)js如何将html表格导出为excel文件(后记)

    js如何将html表格导出为excel文件(后记) 前言 项目前期做了个导出Excel表格的功能,但是经过测试发现只有在IE上才可以正确实现,在Chrome等浏览器中无法实现导出效果.经过上网搜索,尝 ...

  8. 网站开发进阶(二十五)js如何将html表格导出为excel文件

    js如何将html表格导出为excel文件        赠人玫瑰,手留余香.若您感觉此篇博文对您有用,请花费2秒时间点个赞,您的鼓励是我不断前进的动力,共勉! jsp页面数据导出成excel的方法很 ...

  9. vue将表格导出为excel

    vue将表格导出为excel 一:在项目中需要安装2个依赖项,如下命令: npm install --save file-saver xlsx 二:在vue文件中如下使用即可: <templat ...

随机推荐

  1. 《JavaScript高级程序设计》第5章 Object类型---Array---学习心得

    1.创建数组的方法: 使用Array构造函数: var colors=new Array() var colors=new Array(20)//l创建一个包含20项的数组 var colors=ne ...

  2. BoostrapTable-本地模式(一次性加在所有数据)

    直接上代码 数据: [ { "id": "1001", "name": "yyq", "isAdmin&quo ...

  3. PHP+jQuery实现翻板抽奖(中奖概率算法)

    在电视节目中有一种抽奖形式暂且叫做翻板抽奖,台上有一个墙面,墙面放置几个大方块,主持人或者抽奖者翻开对应的方块即可揭晓中奖结果.类似的抽奖形式还可以应用在WEB中,本文将使用PHP+jQuery为您讲 ...

  4. @Html.Partial,@Html.Action,@Html.RenderPartial,@Html.RenderAction [转]

    @Html.Action:需要有对应的Action,并且Action方法有返回值.(注:处理完业务逻辑同时,也需要返回所需值) @{Html.RenderAction}:需要有对应的Action,Ac ...

  5. codevs原创抄袭题 5960 信使

    题目描述 Description •战争时期,前线有n个哨所,每个哨所可能会与其他若干个哨所之间有通信联系.信使负责在哨所之间传递信息,当然,这是要花费一定时间的(以天为单位).指挥部设在第一个哨所. ...

  6. SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1fa5519] was not registered for synchronization because synchronization is not active

    Creating a new SqlSessionSqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1fa5519] w ...

  7. Visual Studio Code 入门教程

    Extensible and customizable.(可扩展的和可定制的,这是我喜欢它的原因) Want even more features? Install extensions to add ...

  8. mysql的三种索引

    MySQL中的索引分为3种: 1,主键索引:即用主键当唯一索引 2,常规索引:实现方式为B树和哈希表 3,全文索引:实现原理类似倒排索引,常用来查询字段中包含关键字 下面复习下B-TREE和hash- ...

  9. 【起航计划 027】2015 起航计划 Android APIDemo的魔鬼步伐 26 App->Preferences->Preferences from XML 偏好设置界面

    我们在前面的例子Android ApiDemo示例解析(9):App->Activity->Persistent State 介绍了可以使用Shared Preferences来存储一些状 ...

  10. WebRTC协议

    webrtc协议介绍 MDN webrtc协议 ICE 交互式连接建立Interactive Connectivity Establishment (ICE) 是一个允许你的浏览器和对端浏览器建立连接 ...