C#如何表格型数据导出到Excel?
代码如下:
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?的更多相关文章
- html实现类似excel的复杂表格,及导出到excel
1. excellentexport.js https://github.com/jmaister/excellentexport/tree/2.0.3 2.fiddle example https ...
- 纯JS 将table表格导出到excel
html <div > <button type="button" onclick="getXlsFromTbl('tableExcel','myDiv ...
- asp.net将内容导出到Excel,Table表格数据(html)导出EXCEL
代码: /// <summary> /// HTML Table表格数据(html)导出EXCEL /// </summary> /// <param name=&quo ...
- 将HTML表格导出到EXCEL,兼容Firefox,支持中文
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- 使用JavaScript把页面上的表格导出为Excel文件
如果在页面上展示了一个数据表格,而用户想把这个表格导出为Excel文件,那么在要求不高的情况下,可以不通过服务器生成表格,而是直接利用JavaScript的Blob和Object URL特性将表格导出 ...
- Python实现数据库一键导出为Excel表格
依赖 Python2711 xlwt MySQLdb 数据库相关 连接 获取字段信息 获取数据 Excel基础 workbook sheet 案例 封装 封装之后 测试结果 总结 数据库数据导出为ex ...
- 网站开发进阶(三十一)js如何将html表格导出为excel文件(后记)
js如何将html表格导出为excel文件(后记) 前言 项目前期做了个导出Excel表格的功能,但是经过测试发现只有在IE上才可以正确实现,在Chrome等浏览器中无法实现导出效果.经过上网搜索,尝 ...
- 网站开发进阶(二十五)js如何将html表格导出为excel文件
js如何将html表格导出为excel文件 赠人玫瑰,手留余香.若您感觉此篇博文对您有用,请花费2秒时间点个赞,您的鼓励是我不断前进的动力,共勉! jsp页面数据导出成excel的方法很 ...
- vue将表格导出为excel
vue将表格导出为excel 一:在项目中需要安装2个依赖项,如下命令: npm install --save file-saver xlsx 二:在vue文件中如下使用即可: <templat ...
随机推荐
- [inner] bug
这样正确 command: ["sh", "-c", "mysql -h${DC_DB_HOST} -uroot -p${MYSQL_ROOT_PAS ...
- [转]Linq语法二
本文将讲述LINQ的基础查询(此文所有例子都使用LINQ to Object) 在此之前,我们先创建一个用于示例的数据源: Student类:表示学生,包括学号.姓名及班级 Courses类:表示学生 ...
- Flex Validator的小BUG
Flex中对同一控件如TextInput进行多种格式校验的情况下,如不注意,可能导致错误信息不显示的BUG,比如 <fx:Array id="validators"> ...
- Maven常用插件整理
maven内置变量 ${basedir}表示项目根目录,即包含pom.xml文件的目录; ${version}表示项目版本; ${project.basedir}同${basedir}; ${proj ...
- 在thinkpad SL400上U盘安装双系统ubuntu14.10
转自:http://zydky.iteye.com/blog/1674100 上文中装的双系统是centos6.3,因为自己对ubuntu有点熟悉,就装了ubuntu. 笔记本是09年入手的,买了之后 ...
- 谷歌浏览器web worker出现cannot be accessed from origin 'null'错误
cannot be accessed from origin 'null'百度翻译是:无法从原点"null"访问 在别的浏览器都可以,而在唯独在谷歌浏览器不行,查找了一些资料原因大 ...
- Java设计模式—中介者模式
中介者模式是一种并不常用的模式,在此简单阐述阐述. 定义:用一个中介者对象封装一系列的对象交互,中介者使各对象不需要显示地相互作用,从而使耦合松散,而且可以独立地改变它们之间的交互. 类型:行为类模式 ...
- Linux,MD5
Linux 中的 md5 利用 md5 消息摘要算法可以获取任何一件事物的唯一 ID 利用 md5 消息摘要算法可以判断任何一个事物是否被改变过 一致性验证:MD5的典型应用是对一段信息(Messag ...
- HTML:::before和::after伪元素的用法
随笔 - 366 文章 - 0 评论 - 392 ::before和::after伪元素的用法 一.介绍 css3为了区分伪类和伪元素,伪元素采用双冒号写法. 常见伪类——:hover,:li ...
- 第五章 存储过程&触发器
1.前言 2.存储过程和触发器->存储过程 ·理解:是一组SQL命令集合,经过预编译存放在系统中:就像java程序里的方法,可以重复的被调用: 在日常的数据库操作中,会有大量的T-SQL批处理. ...