博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#导出excel
阅读量:6679 次
发布时间:2019-06-25

本文共 10249 字,大约阅读时间需要 34 分钟。

第一种比较实用,Insert添加数据

///         /// 导出数据到Excel并保存        ///         /// DataSet        /// 文件路径        /// excel列名 逗号分割的字符串        /// 数据库列名 逗号分割字符串         /// 
public static bool ExportReportEmail(DataSet ds, string filePath,string columName, string tableName) { if (ds != null && ds.Tables.Count > 0) { System.Data.DataTable sourceTable = ds.Tables[0]; // 使用OleDb驱动程序连接到副本 OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=Excel 8.0;"); using (conn) { conn.Open();// if (sourceTable != null && sourceTable.Rows.Count > 0) { string[] colums = columName.Split(','); string[] tables = tableName.Split(','); for (int i = 0; i < sourceTable.Rows.Count; i++) { // 增加记录 OleDbCommand cmd = new OleDbCommand("INSERT INTO [Sheet1$](" + columName + ") VALUES(" + tableName + ")", conn);                  //循环给列 指定参数 for (int j = 0; j < colums.Length;j++ ) { cmd.Parameters.AddWithValue(tables[j].Trim(), sourceTable.Rows[i][colums[j].Trim()].ToString()); // } cmd.ExecuteNonQuery(); } } } return true; }else return false;}

第二种  写入文件

//这种写入的文件,其实后缀是xls的 文本文档 try            {                long rowRead = 0;                StreamWriter sw = new StreamWriter(Pathname, false, Encoding.GetEncoding("gb2312"));                StringBuilder sb = new StringBuilder();                for (int k = 0; k < sourceTable.Columns.Count; k++)                {                    sb.Append(sourceTable.Columns[k].ColumnName.ToString() + "\t");                }                sb.Append(Environment.NewLine);                for (int i = 0; i < sourceTable.Rows.Count; i++)                {                    rowRead++;                    for (int j = 0; j < sourceTable.Columns.Count; j++)                    {                        sb.Append(sourceTable.Rows[i][j].ToString() + "\t");                    }                    sb.Append(Environment.NewLine);                }                sw.Write(sb.ToString());                sw.Flush();                sw.Close();                return true;            }            catch (Exception ex)            {                return false;            }

 

 第三种  HSSFWorkbook

using Microsoft.Office.Interop.Excel;using NPOI.HSSF.UserModel;using System;using System.Collections.Generic;using System.Data;using System.Data.OleDb;using System.IO;using System.Linq;using System.Reflection;using System.Text;using System.Web;namespace JW.Shop.Common{    public class NopiHelper    {        #region 导出到Excel(仅支持Excel1997-2003)        ///         /// 由DataTable导出Excel        ///         /// 要导出的数据源        /// 工作表名        /// 工作表列名        /// 
Excel工作表
private static Stream ExportDataTableToExcel(System.Data.DataTable sourceTable, string sheetName, string columnNames) { HSSFWorkbook workbook = new HSSFWorkbook(); MemoryStream ms = new MemoryStream(); HSSFSheet sheet = workbook.CreateSheet(sheetName) as HSSFSheet; HSSFRow headerRow = sheet.CreateRow(0) as HSSFRow; // handling header. if (!string.IsNullOrEmpty(columnNames)) { string[] cols = columnNames.Split(','); for (int i = 0; i < sourceTable.Columns.Count; i++) { headerRow.CreateCell(sourceTable.Columns[i].Ordinal).SetCellValue(cols[i]); } } else { foreach (DataColumn column in sourceTable.Columns) headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName); } // handling value. int rowIndex = 1; foreach (DataRow row in sourceTable.Rows) { HSSFRow dataRow = sheet.CreateRow(rowIndex) as HSSFRow; foreach (DataColumn column in sourceTable.Columns) { dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString()); } rowIndex++; } workbook.Write(ms); ms.Flush(); ms.Position = 0; sheet = null; headerRow = null; workbook = null; return ms; } /// /// 导出数据到Excel并下载(仅支持Excel1997-2003) /// /// 要导出的数据源 /// Excel的工作表名 /// 工作表列名(逗号分隔) /// 下载保存Excel的文件名 ///
Excel工作表
public static bool ExportDownloadExcel(System.Data.DataTable sourceTable, string sheetName, string columnNames, string fileName) { try { MemoryStream ms = ExportDataTableToExcel(sourceTable, sheetName, columnNames) as MemoryStream; HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ClearContent(); HttpContext.Current.Response.ClearHeaders(); HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8)); HttpContext.Current.Response.ContentType = "application/ms-excel"; // application/octet-stream HttpContext.Current.Response.HeaderEncoding = Encoding.UTF8;// System.Text.Encoding.GetEncoding("GB2312"); HttpContext.Current.Response.ContentEncoding = Encoding.UTF8; HttpContext.Current.Response.BinaryWrite(ms.ToArray()); HttpContext.Current.Response.Flush(); //HttpContext.Current.Response.End(); ms.Close(); ms = null; return true; } catch (Exception) { return false; } } /// /// 由DataSet导出Excel /// /// 要导出的数据源 /// 工作表名 /// 工作表列名 ///
Excel工作表
private static Stream ExportDataSetToExcel(DataSet sourceDs, string[] sheetNames, string[] columnNames) { HSSFWorkbook workbook = new HSSFWorkbook(); MemoryStream ms = new MemoryStream(); //string[] sheetNames = sheetName.Split(','); for (int i = 0; i < sheetNames.Length; i++) { HSSFSheet sheet = workbook.CreateSheet(sheetNames[i]) as HSSFSheet; HSSFRow headerRow = sheet.CreateRow(0) as HSSFRow; // handling header. if (columnNames.Length > 0 && (!string.IsNullOrEmpty(columnNames[i]))) { string[] cols = columnNames[i].Split(','); for (int j = 0; j < cols.Length; j++) { headerRow.CreateCell(sourceDs.Tables[i].Columns[j].Ordinal).SetCellValue(cols[j]); } } else { foreach (DataColumn column in sourceDs.Tables[i].Columns) headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName); } // handling value. int rowIndex = 1; foreach (DataRow row in sourceDs.Tables[i].Rows) { HSSFRow dataRow = sheet.CreateRow(rowIndex) as HSSFRow; if (columnNames.Length > 0 && (!string.IsNullOrEmpty(columnNames[i]))) { string[] cols = columnNames[i].Split(','); for (int j = 0; j < cols.Length; j++) { dataRow.CreateCell(sourceDs.Tables[i].Columns[j].Ordinal).SetCellValue(row[j].ToString()); } } else { foreach (DataColumn column in sourceDs.Tables[i].Columns) { dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString()); } } rowIndex++; } } workbook.Write(ms); ms.Flush(); ms.Position = 0; workbook = null; return ms; } /// /// 导出数据到Excel并下载(仅支持Excel1997-2003) /// /// 要导出数据的DataTable /// 工作表名 /// 工作表列名 /// 指定Excel工作表名称 ///
Excel工作表
public static bool ExportDownloadExcel(DataSet sourceDs, string[] sheetName, string[] columnNames, string fileName) { try { MemoryStream ms = ExportDataSetToExcel(sourceDs, sheetName, columnNames) as MemoryStream; HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ClearContent(); HttpContext.Current.Response.ClearHeaders(); HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8)); HttpContext.Current.Response.ContentType = "application/ms-excel"; // application/octet-stream HttpContext.Current.Response.HeaderEncoding = Encoding.UTF8;// System.Text.Encoding.GetEncoding("GB2312"); HttpContext.Current.Response.ContentEncoding = Encoding.UTF8; HttpContext.Current.Response.BinaryWrite(ms.ToArray()); HttpContext.Current.Response.Flush(); //HttpContext.Current.Response.End(); ms.Close(); ms = null; return true; } catch (Exception) { return false; } } #endregion}}
View Code

 

 

转载于:https://www.cnblogs.com/shushan/p/3780288.html

你可能感兴趣的文章
新疆之春(二)魂牵梦绕赛里木湖
查看>>
解析el表达式出错
查看>>
vmware实现nat上网
查看>>
Linux一键安装Aria2+Yaaw+FileManager实现BT磁力下载,并在线查看/观看
查看>>
unity3d zegui 按钮图标更换 不成功
查看>>
安装wxPHP后,apache无法启动
查看>>
android判断是否连接网络
查看>>
我的友情链接
查看>>
JNI字段描述符“([Ljava/lang/String;)V”
查看>>
sqlite 打开数据库
查看>>
http://xpleaf.blog.51cto.com/
查看>>
Thrift使用教程(Java版本)
查看>>
我的友情链接
查看>>
通过SSH证书实现Putty免密码登录CentOS
查看>>
Java IO类库之Bits
查看>>
ERROR 1217 (23000): Cannot delete or update a pare
查看>>
oracle 11g RAC搭建 ASM存储
查看>>
函数学习-bytearray()
查看>>
CentOS7安装配置telnet-server
查看>>
GitOSC和GitHub上传项目
查看>>