WinForm导出DataSet到Excel
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;
using System.Data.SqlClient;
using Microsoft.Office.Core;
using System.Diagnostics;
using System.Reflection;
using Microsoft.Office.Interop.Excel; //添加引用-->COM-->Microsoft Excel 12.0 Object Library namespace TestExcel
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private static string connStr = "User Id=sa;Password=123456;Data Source=.;Initial Catalog=TDRDB;"; //查询产品
public static List<Object> getProducList()
{
SqlConnection conn = null;
List<Object> producList = new List<Object>();
string sqlStr = string.Format("select * from production order by type"); try
{
using (conn = new SqlConnection(connStr))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sqlStr, conn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Production p = new Production();
p.Id = int.Parse(Convert.ToString(dr["ID"]));
p.Name = Convert.ToString(dr["name"]);
p.Type = Convert.ToString(dr["type"]);
p.Pic = Convert.ToString(dr["pic"]);
p.NetPrice = Double.Parse(Convert.ToString(dr["netPrice"]));
p.GrossPrice = Double.Parse(Convert.ToString(dr["grossPrice"]));
p.Mark = Convert.ToString(dr["mark"]);
producList.Add(p);
} }
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
conn.Close();
conn.Dispose();
}
return producList; }
private void button1_Click(object sender, EventArgs e)
{ DataSet ds = new DataSet();
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.AddRange(new DataColumn[] { new DataColumn("编号"), new DataColumn("名称"), new DataColumn("型号"), new DataColumn("图片"), new DataColumn("净价"), new DataColumn("毛价"), new DataColumn("备注"), });
for (int i = 0; i < getProducList().Count; i++)
{
Production produc=(Production)getProducList()[i];
String[] rows = new String[] { produc.Id.ToString(), produc.Name, produc.Type, produc.Pic, produc.NetPrice.ToString(), produc.GrossPrice.ToString(), produc.Mark };
dt.Rows.Add(rows);
}
ds.Tables.Add(dt);
ExportToExcel(ds, "D:\\产品信息"); } public static void ExportToExcel(DataSet dataSet, string fileName)
{ //Excel程序
Microsoft.Office.Interop.Excel.Application excelApplication = new Microsoft.Office.Interop.Excel.Application();
excelApplication.DisplayAlerts = false;
//工作簿
Workbook workbook = excelApplication.Workbooks.Add(Missing.Value);
//上一个工作簿
Worksheet lastWorksheet = (Worksheet)workbook.Worksheets.get_Item(workbook.Worksheets.Count);
//空白工作簿
Worksheet newSheet = (Worksheet)workbook.Worksheets.Add(Type.Missing, lastWorksheet, Type.Missing, Type.Missing); foreach (System.Data.DataTable dt in dataSet.Tables)
{
newSheet.Name = dt.TableName; for (int col = 0; col < dt.Columns.Count; col++)
{
newSheet.Cells[1, col + 1] = dt.Columns[col].ColumnName;
}
for (int row = 0; row < dt.Rows.Count; row++)
{
for (int col = 0; col < dt.Columns.Count; col++)
{
newSheet.Cells[row + 2, col + 1] = dt.Rows[row][col].ToString();
}
}
} try
{
newSheet.Cells.Font.Size = 12;
((Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.get_Item(1)).Delete();
((Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.get_Item(1)).Delete();
((Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.get_Item(1)).Delete();
//((Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.get_Item(1)).Activate();
workbook.Close(true, fileName, System.Reflection.Missing.Value);
MessageBox.Show("成功导出Excel,请查看!", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
catch (Exception e)
{
throw e;
}
finally
{
excelApplication.Quit();
Process[] excelProcesses = Process.GetProcessesByName("EXCEL");
DateTime startTime = new DateTime(); int processId = 0;
for (int i = 0; i < excelProcesses.Length; i++)
{
if (startTime < excelProcesses[i].StartTime)
{
startTime = excelProcesses[i].StartTime;
processId = i;
}
} if (excelProcesses[processId].HasExited == false)
{
excelProcesses[processId].Kill();
}
} } }
}
WinForm导出DataSet到Excel的更多相关文章
- winform 导出datagridview 到excel
数据不多可以用下面的方式方法,如果数据较大,不建议这样使用,可能会比较卡如果电脑上没有Microsoft.Office.Interop.Excel.dll去找DLL下载站下载即可 需要先导入这个dll ...
- C#winform导出数据到Excel的类
/// <summary> /// 构造函数 /// </summary> public ExportData() { } /// <summary> /// 保存 ...
- c# 导出DataSet到excel
public static bool ExportToExcel_dataSet(string queryNo, string conditions) { bool _bl = false; try ...
- Delphi 导出数据至Excel的7种方法【转】
一; delphi 快速导出excel uses ComObj,clipbrd; function ToExcel(sfilename:string; ADOQuery:TADOQuery): ...
- Delphi 导出数据至Excel的7种方法
一; delphi 快速导出excel uses ComObj,clipbrd; function ToExcel(sfilename:string; ADOQuery:TADOQuery):bool ...
- 循序渐进开发WinForm项目(5)--Excel数据的导入导出操作
随笔背景:在很多时候,很多入门不久的朋友都会问我:我是从其他语言转到C#开发的,有没有一些基础性的资料给我们学习学习呢,你的框架感觉一下太大了,希望有个循序渐进的教程或者视频来学习就好了. 其实也许我 ...
- 【C#常用方法】2.DataTable(或DataSet)与Excel文件之间的导出与导入(使用NPOI)
DataTable与Excel之间的互导 1.项目添加NPOI的引用 NPOI项目简介: NPOI是一个开源的C#读写Excel.WORD等微软OLE2组件文档的项目,特点是可以在没有安装Office ...
- C# WinForm 导出导入Excel/Doc 完整实例教程[使用Aspose.Cells.dll]
[csharp] view plain copy 1.添加引用: Aspose.Cells.dll(我们就叫工具包吧,可以从网上下载.关于它的操作我在“Aspose.Cells操作说明 中文版 下载 ...
- 【转】c# winform DataGridView导出数据到Excel中,可以导出当前页和全部数据
准备工作就是可以分页的DataGridView,和两个按钮,一个用来导出当前页数据到Excel,一个用来导出全部数据到Excel 没有使用SaveFileDialog,但却可以弹出保存对话框来 先做导 ...
随机推荐
- vmware Horizon 7 与远程桌面(mstsc)兼容性问题解决办法
关于Horizon 7 Agent与远程桌面(mstsc)兼容性问题解决办法 在Horizon 7环境中,在桌面模板安装了Horizon Agent后,就无法直接通过微软的远程桌面(mstsc)工具连 ...
- 11.7 【Linq】在查询表达式和点标记之间作出选择
11.7.1 需要使用点标记的操作 最明显的必须使用点标记的情形是调用 Reverse . ToDictionary 这类没有相应的查询表达式语法的方法.然而即使查询表达式支持你要使用的查询操作符,也 ...
- webstorm中vue项目--运行配制
## npm搭建的项目,需要运行npm run dev来启动 webstorm作为一款优秀的编辑器,通过配置运行设置,达到一键运行 1.添加node.js配置 2.configuration-> ...
- Python检测删除你的好友-wxpy模块(发送特殊字符式)
下面是代码: from wxpy import *import timeprint("本软件采用特殊字符检测,即对方收不到任何信息!")print("或许某个版本微信就会 ...
- netty helloWord (一)
什么是nettty netty是基于javaNio模型的网络编程框架.很多框架底层也是用netty实现的 比如dubbo 与NIO的区别 1.简化了API的使用.基于事件驱动.只需要在对应的事件写相应 ...
- poj 2186 强连通+缩点
题意:有一群牛,求被所有牛都认可的牛的个数 每个连通分量建一个缩点,出度为零的缩点包含的点的个数即为要求值 如果有多个出度为零的,直接输出零,否则输出那唯一一个出度为零的缩点包含的点的个数 #incl ...
- 消息队列Rabbit安装
先安装elang 再安装Rabbit *Rabbit安装路径不能有空格 安装完成
- 20160223.CCPP体系具体解释(0033天)
程序片段(01):MyArray.h+MyArray.c+main.c 内容概要:数组库 ///MyArray.h #pragma once #define DT int//类型通用 typedef ...
- HDU 2295
二分答案+重复覆盖.注意返回的条件哦,不能光套模板. #include <iostream> #include <cstdio> #include <cstring> ...
- pl/sql developer br 文件
pl/sql developer br 文件 Version=1 RightMargin=72 Indent=2 UseTabCharacter=FALSE TabCharacterSize=2 Al ...