Winform数据导出Execl小工具
前台界面.cs文件
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Unis.Realtime.Data;
using Unis.Realtime.Drivers; namespace ExportRTData
{
public partial class ExportData : Form
{
#region 声明 /// <summary>
/// 定义单线程文件
/// </summary>
BackgroundWorker worker = new BackgroundWorker();
/// <summary>
/// 定义终止操作
/// </summary>
private ManualResetEvent manualReset = new ManualResetEvent(true);
/// <summary>
/// 计算一共要执行的总次数
/// </summary>
public int Count = ;
/// <summary>
/// 计算执行了多少
/// </summary>
public int ExcuteCount = ;
/// <summary>
/// 错误
/// </summary>
private bool Error = true;
/// <summary>
/// 实时库连接
/// </summary>
private RealtimeClient rt = RealtimeClient.Create("RTDB"); #endregion #region 构造函数 /// <summary>
/// 构造函数
/// </summary>
public ExportData()
{
InitializeComponent();
worker.WorkerSupportsCancellation = true;
} #endregion /// <summary>
/// 页面加载事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ExportData_Load(object sender, EventArgs e)
{
string strStartTime = ConfigurationManager.AppSettings["StartTime"];
string strEndTime = ConfigurationManager.AppSettings["EndTime"];
string strInterval = ConfigurationManager.AppSettings["Interval"]; this.tbInterval.Text = strInterval;
this.dtStartTime.Text = strStartTime;
this.dtEndTime.Text = strEndTime;
} /// <summary>
/// 开始导出数据事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnStart_Click(object sender, EventArgs e)
{
if (DateTime.Parse(this.dtStartTime.Text) > DateTime.Parse(this.dtEndTime.Text))
{
MessageBox.Show("开始时间不能大于结束时间");
return;
} #region 保存配置信息 string strStartTime = this.dtStartTime.Text;
string strEndTime = this.dtEndTime.Text;
string strInterval = this.tbInterval.Text; Configuration cf = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
cf.AppSettings.Settings["StartTime"].Value = strStartTime;
cf.AppSettings.Settings["EndTime"].Value = strEndTime;
cf.AppSettings.Settings["Interval"].Value = strInterval;
cf.Save();
ConfigurationManager.RefreshSection("appSettings"); #endregion #region 控制控件 this.dtStartTime.Enabled = false;
this.dtEndTime.Enabled = false;
this.btnStart.Enabled = false;
this.btnStop.Enabled = true;
this.tbInterval.ReadOnly = true; #endregion SetWorkerMethod();
this.lbRate.Items.Clear();
worker.RunWorkerAsync();
} /// <summary>
/// 设定线程事件
/// </summary>
protected void SetWorkerMethod()
{
worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.WorkerSupportsCancellation = true;
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
} /// <summary>
/// 线程工作事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
workExportData(worker);
} /// <summary>
/// 历史数据导出
/// </summary>
/// <param name="bk"></param>
private void workExportData(BackgroundWorker bk)
{
try
{
// 连接字符串
string xlsPath = Application.StartupPath + "\\FanStencil\\导数据清单.xlsx";
string strCon = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + xlsPath + ";Extended Properties='Excel 8.0; HDR=Yes; IMEX=1'";
//此连接可以操作.xls与.xlsx文件 (支持Excel2003 和 Excel2007 的连接字符串)
//备注: "HDR=yes;"是说Excel文件的第一行是列名而不是数据,"HDR=No;"正好与前面的相反。
// "IMEX=1 "如果列中的数据类型不一致,使用"IMEX=1"可必免数据类型冲突。 OleDbConnection conn = new OleDbConnection(strCon);
conn.Open();
DataTable dtFanPoint = new DataTable();
string strExcel = "select * from [Sheet1$]";
OleDbDataAdapter myCommand = new OleDbDataAdapter(strExcel, strCon);
myCommand.Fill(dtFanPoint); Count = dtFanPoint.Rows.Count;
bk.ReportProgress(ExcuteCount, "读到的风总数为:" + dtFanPoint.Rows.Count.ToString() + "."); int columnCount = dtFanPoint.Columns.Count;
for (int i = ; i < dtFanPoint.Rows.Count; i++)
{
//判断是否取消线程执行
while (bk.CancellationPending)
{
System.Threading.Thread.Sleep();
//将信息显示到前台UI
bk.ReportProgress(, "导出已经停止,停止时间为:" + DateTime.Now.ToString("HH:mm:ss") + ",若要再导出请点击开始!");
return;
} bk.ReportProgress(ExcuteCount, "风数据:" + dtFanPoint.Rows[i][].ToString()); DataRow drFanPoint = dtFanPoint.Rows[i];
DataTable dtValueData = new DataTable(); dtValueData = dtFanPoint.Copy();
dtValueData.Clear();
dtValueData.Rows.Add(dtFanPoint.Rows[i].ItemArray); //添加数据行
dtValueData.Columns.RemoveAt();
dtValueData.Columns[].ColumnName = "时间"; for (int j = ; j < columnCount; j++)
{
string strPoint = dtFanPoint.Rows[i][j].ToString();
PointModel pointModel = new PointModel() { Name = strPoint };
List<PointData> listPointData = rt.Hist(pointModel, DateTime.Parse(this.dtStartTime.Text), DateTime.Parse(this.dtEndTime.Text), TimeSpan.Parse("00:" + this.tbInterval.Text.Trim() + ":00")); for (int k = ; k < listPointData.Count; k++)
{
if (j == )
{
dtValueData.Rows.Add(new object[] { listPointData[k].Time });
}
dtValueData.Rows[k + ][j - ] = listPointData[k].Value;
}
} string filePath = Application.StartupPath + "\\HistoryData\\";
ExeclHelper.ExportDataToExcel(dtValueData, filePath, drFanPoint[].ToString()); ExcuteCount += ;
bk.ReportProgress(ExcuteCount, "风数据已导出完毕:" + dtFanPoint.Rows[i][].ToString() + ".");
}
bk.ReportProgress(ExcuteCount, "数据已全部成功导出!");
}
catch (Exception ex)
{
Error = false;
MessageBox.Show("导出异常:" + ex.Message);
bk.ReportProgress(ExcuteCount, "异常:" + ex.Message + ","); }
} private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (Error == true)
MessageBox.Show("数据成功", "提示");
else
MessageBox.Show("数据导出异常,见文本提示", "提示");
} /// <summary>
/// 报告异步操作的进度
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
string strRan = e.UserState.ToString(); if (strRan.LastOrDefault() == '.')
{
//走滚动条添加进度
this.pgbExport.Maximum = Count;
this.pgbExport.Value = e.ProgressPercentage;
this.lbRate.Items.Add(e.UserState.ToString());
}
else if (strRan.LastOrDefault() == ',')
{
Error = true;
//添加错误状态
//errorlist.Add(e.UserState.ToString());
this.lbRate.Items.Add(e.UserState.ToString());
//errorInformation(e.UserState.ToString(), false);
}
else if (strRan.LastOrDefault() == '!')
{
//数据处理完毕
this.dtStartTime.Enabled = true;
this.dtEndTime.Enabled = true;
this.btnStart.Enabled = true;
this.btnStop.Enabled = false;
this.tbInterval.ReadOnly = false;
}
else
{
this.lbRate.Items.Add(e.UserState.ToString() + "正在处理!");
}
} /// <summary>
/// 停止导出数据事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnStop_Click(object sender, EventArgs e)
{
if (worker.IsBusy)
{
worker.ReportProgress(, "数据导出已经停止.");
worker.CancelAsync();
} this.dtStartTime.Enabled = true;
this.dtEndTime.Enabled = true;
this.btnStart.Enabled = true;
this.btnStop.Enabled = false;
this.tbInterval.ReadOnly = false;
} }
}
ExeclHelper.cs,将DataTable输出到Execl中
using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; namespace ExportRTData
{
public class ExeclHelper
{
/// <summary>
/// 将DataTable的数据导出到Excel中。
/// </summary>
/// <param name="dt">DataTable</param>
/// <param name="xlsFileDir">导出的Excel文件存放目录</param>
/// <param name="strTitle">Excel表的标题</param>
/// <returns>Excel文件名</returns>
public static string ExportDataToExcel(System.Data.DataTable dt, string xlsFileDir, string strTitle)
{
if (dt == null) return "";
Microsoft.Office.Interop.Excel.ApplicationClass excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
Microsoft.Office.Interop.Excel.Workbooks workBooks = excel.Workbooks;
Microsoft.Office.Interop.Excel.Workbook workBook = workBooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
//Microsoft.Office.Interop.Excel.Worksheet workSheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Worksheets[1];
int titleRowsCount = ; int rowCount = dt.Rows.Count + ;
int colCount = dt.Columns.Count;
object[,] dataArray = new object[rowCount, colCount]; if (strTitle != null && strTitle.Trim() != "")
{
titleRowsCount = ;
excel.get_Range(excel.Cells[, ], excel.Cells[, dt.Columns.Count]).Font.Bold = true;
excel.get_Range(excel.Cells[, ], excel.Cells[, dt.Columns.Count]).Font.Size = ;
excel.get_Range(excel.Cells[, ], excel.Cells[, dt.Columns.Count]).MergeCells = true;
dataArray[, ] = strTitle;
} if (!System.IO.Directory.Exists(xlsFileDir))
{
System.IO.Directory.CreateDirectory(xlsFileDir);
} strTitle = strTitle.Replace(":", ":");
string strFileName = strTitle + ".xlsx";
string tempColumnName = ""; for (int i = ; i < rowCount - ; i++)
{
for (int j = ; j < colCount; j++)
{
if (i == )
{
tempColumnName = dt.Columns[j].ColumnName.Trim();
dataArray[titleRowsCount, j] = tempColumnName;
}
dataArray[i + titleRowsCount + , j] = dt.Rows[i][j];
}
}
excel.get_Range("A1", excel.Cells[rowCount, colCount]).Value2 = dataArray; excel.get_Range(excel.Cells[titleRowsCount + , ], excel.Cells[titleRowsCount + , dt.Columns.Count]).Font.Bold = true;
excel.get_Range(excel.Cells[, ], excel.Cells[titleRowsCount + + dt.Rows.Count, dt.Columns.Count]).HorizontalAlignment = XlVAlign.xlVAlignCenter;
excel.get_Range(excel.Cells[, ], excel.Cells[titleRowsCount + + dt.Rows.Count, dt.Columns.Count]).EntireColumn.AutoFit(); workBook.Saved = true;
workBook.SaveCopyAs(xlsFileDir + strFileName);
//System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet);
//workSheet = null;
System.Runtime.InteropServices.Marshal.ReleaseComObject(workBook);
workBook = null;
workBooks.Close();
System.Runtime.InteropServices.Marshal.ReleaseComObject(workBooks);
workBooks = null;
excel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
excel = null;
return strFileName;
}
}
}
Winform数据导出Execl小工具的更多相关文章
- asp.net大数据导出execl实现分开压缩并下载
asp.net大数据导出execl实现分开压缩并下载 /// <summary> /// 导出数据到EXCEL 多个表的 /// </summary> /// <para ...
- 使用springboot和easypoi进行的数据导出的小案例
在这个案例中使用的有springboot和easypoi进行数据导出到excel中 yml文件是这样的: server: port: 8080 spring: datasource: url: jdb ...
- WPF数据爬取小工具-某宝推广位批量生成,及订单爬取 记:接单最痛一次的感悟
项目由来:上月闲来无事接到接到一个单子,自动登录 X宝平台,然后重定向到指定页面批量生成推广位信息:与此同时自动定时同步订单数据到需求提供方的Java服务. 当然期间遇到一个小小的问题就是界面样式的问 ...
- pandas数据导出Execl
脚本主要功能是将数据库查询到的结果,通过pandas写到到execl文件中. #!/usr/bin/env python #-*- coding: utf8 -*- from sqlalchemy i ...
- asp.net中导出Execl的方法
一.asp.net中导出Execl的方法: 在 asp.net中导出Execl有两种方法,一种是将导出的文件存放在服务器某个文件夹下面,然后将文件地址 输出在浏览器上:一种是将文件直接将文件输出流写给 ...
- c 小工具的使用
1. 这是一个gps 数据过滤的小工具,目的是过滤到gps数据中不符合要求的数据,然后转为json 数据 需要两个小工具 bermuda.c ------> 过滤一定范围的数据 geo2j ...
- 懒人小工具1:winform自动生成Model,Insert,Select,Delete以及导出Excel的方法
懒人小工具2:T4自动生成Model,Insert,Select,Delete以及导出Excel的方法 github地址:https://github.com/Jimmey-Jiang/J ...
- sqluldr2 oracle直接导出数据为文本的小工具使用
近期客户有需求,导出某些审计数据,供审计人进行核查,只能导出成文本或excel格式的进行查看,这里我们使用sqluldr2工具进行相关数据的导出. oracle导出数据为文本格式比较麻烦,sqluld ...
- 【基于WinForm+Access局域网共享数据库的项目总结】之篇二:WinForm开发扇形图统计和Excel数据导出
篇一:WinForm开发总体概述与技术实现 篇二:WinForm开发扇形图统计和Excel数据导出 篇三:Access远程连接数据库和窗体打包部署 [小记]:最近基于WinForm+Access数据库 ...
随机推荐
- JSP 数据库连接类 MySql数据库
数据库连接类的主要功能是连接数据库并且获得连接对象,以及关闭数据库.通过创建该类的实例,调用其中的方法,以避免重复操作. package chapter13; import java.sql.*; p ...
- [Android自定义控件] Android自定义控件
转载自:http://blog.163.com/ppy2790@126/blog/static/103242241201382210910473/ 开发自定义控件的步骤: 1.了解View的工作原理 ...
- 移动平台对 meta 标签的定义
一.meta 标签分两大部分:HTTP 标题信息(http-equiv)和页面描述信息(name). 1.http-equiv 属性的 Content-Type 值(显示字符集的设定) 说明:设定页面 ...
- ✡ leetcode 164. Maximum Gap 寻找最大相邻数字差 --------- java
Given an unsorted array, find the maximum difference between the successive elements in its sorted f ...
- 反编译dtsi
dtsi机制是linux kernel为了适配多设备做出来的模块,产品线拉的较长的话用它来控制最合适不过了.初步阅读了下代码和接口清晰简洁. 这个东东出来的时候xml/json应该比较成熟了,疑惑的是 ...
- Restful 支持 自定义序列化
[ServiceContract] [ServiceKnownType(typeof(HRAwardObject))] [ServiceKnownType(typeof(WorkflowBasicIn ...
- android四大组件之ContentProvider(一)
ContentProvider学习笔记 1. ContentProvider基本概念 ContentProvider向我们提供了我们在应用程序之间共享数据的一种机制,虽然采用文件和SharedPref ...
- Java开发常用Linux命令
1.查找文件 find / -name filename.txt根据名称查找/目录下的filename.txt文件. find . -name "*.xml"递归查找所有的xml文 ...
- ASP.NET MVC Web API 学习笔记---第一个Web API程序
http://www.cnblogs.com/qingyuan/archive/2012/10/12/2720824.html GetListAll /api/Contact GetListBySex ...
- WebApi:自定义筛选器
最近在项目中有这样一个需求,记录每次Api访问的调用时间,运行时间,传入数据,返回数据等信息. 第一反应就是添加一个类,用来实现相应的功能,然后在方法的代码中添加,但是这样的话,需要修改所有的方法的代 ...