using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Reflection;
namespace ExcelPrj
{
/// <summary>
/// Excel 系统中的主文件Excel.exe 本身就是 COM 组件,通过在.NET 项目中引用Exel.exe 文件可以实现对Excel 的功能控制
/// 与COM 组件相互操作是通过使用"包装类"(Wrapper Class) 和"代理"(Proxy) 的机制实现的.包装类使.NET 程序可以识别COM 组件提供的接口,而代理类则是提供对 COM 接口的访问
/// </summary>
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button3_Click(object sender, EventArgs e)
{
ExportTasks(Bind(), dataGridView1);
}
//如果 Excel 安装在计算机上,侧导出表格内容到 Excel
public void ExportTasks(DataSet TasksData, DataGridView TasksGridView)
{
// 定义要使用的Excel 组件接口
// 定义Application 对象,此对象表示整个Excel 程序
Microsoft.Office.Interop.Excel.Application excelApp = null ;
// 定义Workbook对象,此对象代表工作薄
Microsoft.Office.Interop.Excel.Workbook workBook;
// 定义Worksheet 对象,此对象表示Execel 中的一张工作表
Microsoft.Office.Interop.Excel.Worksheet ws=null;
//定义Range对象,此对象代表单元格区域
Microsoft.Office.Interop.Excel.Range r;
int row = 1; int cell = 1;
try
{
//初始化 Application 对象 excelApp
excelApp = new Microsoft.Office.Interop.Excel.Application();
//在工作薄的第一个工作表上创建任务列表
workBook = excelApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
ws =(Worksheet)workBook.Worksheets[1];
// 命名工作表的名称为 "Task Management"
ws.Name = "Task Management";
#region 创建表格的列头
// 遍历数据表中的所有列
foreach (DataGridViewColumn cs in TasksGridView.Columns)
{
// 假如并不想把主键也显示出来
if (cs.HeaderText != "编号")
{
ws.Cells[row, cell] = cs.HeaderText;
r = (Range)ws.Cells[row, cell];
ws.get_Range(r, r).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
//此处用来设置列的样式
cell++;
}
}
// 创建行,把数据视图记录输出到对应的Excel 单元格
for (int i = 2; i < TasksData.Tables[0].Rows.Count; i++)
{
for (int j = 1; j < TasksData.Tables[0].Columns.Count; j++)
{
ws.Cells[i, j] = TasksData.Tables[0].Rows[i][j].ToString();
// r = (Range)ws.Cells[i,j];
Range rg = (Range)ws.get_Range(ws.Cells[i, j], ws.Cells[i, j]);
rg.EntireColumn.ColumnWidth = 20;
// rg.Columns.AutoFit();
rg.NumberFormatLocal = "@";
}
}
#endregion
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
//显示 Excel
excelApp.Visible = true;
}
private void button5_Click(object sender, EventArgs e)
{
DataSet ds = Bind();
dataGridView1.DataSource = ds.Tables[0];
}
private DataSet Bind()
{
SqlConnection conn = new SqlConnection("Server=.;Database=testManage;Integrated Security=SSPI");
SqlDataAdapter da = new SqlDataAdapter("select FNumber,FExamNum,FName,FSex,FJobAdd,FCardID,FBirDate from stuInfo", conn);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
private void button2_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Title = "请选择将导出的EXCEL文件存放路径";
sfd.FileName = System.DateTime.Now.ToShortDateString() + "-学生信息";
sfd.Filter = "Excel文档(*.xls)|*.xls";
sfd.ShowDialog();
if (sfd.FileName != "")
{
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
if (excelApp == null)
{
MessageBox.Show("无法创建Excel对象,可能您的机器未安装Excel");
}
else
{
Microsoft.Office.Interop.Excel.Workbooks workbooks = excelApp.Workbooks;
Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Microsoft.Office.Interop.Excel.Worksheet worksheet =(Worksheet) workbook.Worksheets[1];
DataSet ds=Bind();
for (int i = 1; i < ds.Tables[0].Rows.Count; i++)
{
for (int j = 1; j < ds.Tables[0].Columns.Count;j++ )
{
if (i == 1)
{
worksheet.Cells[i, j] = dataGridView1.Columns[j].HeaderText;
}
worksheet.Cells[i+1, j] = ds.Tables[0].Rows[i][j].ToString();
}
}
//保存方式一:保存WorkBook
//workbook.SaveAs(@"F:/CData.xls",
// Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,
// Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,Missing.Value,Missing.Value,Missing.Value,
// Missing.Value,Missing.Value);
//保存方式二:保存WorkSheet
// worksheet.SaveAs(@"F:/CData2.xls",
// Missing.Value, Missing.Value, Missing.Value, Missing.Value,
// Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
////保存方式三
//workbook.Saved = true;
//workbook.SaveCopyAs(sfd.FileName);
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;
excelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
excelApp = null;
MessageBox.Show("导出Excel完成!");
}
}
}
private void button4_Click(object sender, EventArgs e)
{
string strExcelFileName = @"F://2007-07-16-学生信息.xls";
string strSheetName = "sheet1";
#region Aspnet 操作Excel 正确
////源的定义
//string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = " + strExcelFileName + ";Extended Properties ='Excel 8.0;HDR=NO;IMEX=1'";
////Sql语句
//string strExcel = "select * from [" + strSheetName + "$]";
////定义存放的数据表
//DataSet ds = new DataSet();
////连接数据源
//OleDbConnection conn = new OleDbConnection(strConn);
//conn.Open();
////适配到数据源
//OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, conn);
//adapter.Fill(ds,"res");
//conn.Close();
//// 一般的情况下. Excel 表格的第一行是列名
//dataGridView2.DataSource = ds.Tables["res"];
#endregion
#region COM 组件读取复杂Excel
Microsoft.Office.Interop.Excel.Application excelApp = null;
Microsoft.Office.Interop.Excel.Workbook workBook;
Microsoft.Office.Interop.Excel.Worksheet ws = null;
try
{
excelApp = new Microsoft.Office.Interop.Excel.Application();
workBook = excelApp.Workbooks.Open(@"F://Book1.xls", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
ws = (Worksheet)workBook.Worksheets[1];
//Excel 默认为 256 列..
MessageBox.Show(ws.Cells.Columns.Count.ToString());
excelApp.Quit();
}
catch (Exception ex)
{
throw ex;
}
#endregion
}
}
}
相关推荐
C#实现视频播放Windows Media Player源代码(最好用)
C# 源代码 本人在项目中改改就可以用了,很不错。 功能:使用Windows Media Player播放音乐,视频,支持 WAV、MID、MP3、MPG、AVI、ASF、WMV、RM、RMVB等文件。 技术:C# + WinForm 版本:Microsoft Visual Studio 2008 上开发 实现功能: 1.选择文件播放 2.设置播放器的属性 3.批量添加文件 4.批量将列表中的文件加到播放器列表 5.显示当前播放的文件,变背景色 6.本程序支持Windows Media Player中所有能播放的文件格式。 插件: 必须安装 RealoneED.exe 让windowsMediaPlayer支持RMRMVB文件 WindowsMediaPlayer播放器经过9.0的测试,基本版本未试过。
c# winform实例大全(198个Csharp WinForm实例源码)
c# winform实例大全(198个Csharp WinForm实例源码)
C# winform联合Access进销存软件系统(带数据库文件、源代码,可直接用)0803.zip
C# winform联合Access进销存软件系统(带数据库文件、源代码,可直接用)
VS2005[C#] 操作 Excel 全攻略(转贴)
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using Microsoft.Office.Interop.Excel;
C# WinForm Datagridview分页+增删改+导航+导出word-exel
如题,C# WinForm Datagridview分页+增删改+导航+导出word-exel,代码写的很清楚,有注释。。几乎每句都有。。 mssql数据库自己配置,已打包在内,只消附加数据库,然后更改app.config既可。 调试不出来,或者调试报错的加Q :455105775
自定义winform 窗口标题栏
自定义winform 窗口标题栏 主要代码 public partial class ZForm : Form { private bool moving = false; private Point oldMousePosition; public new FormBorderStyle FormBorderStyle { get { return base.FormBorderStyle; } set { if (value != FormBorderStyle.Sizable && value != FormBorderStyle.SizableToolWindow) { titlepanel.Controls.Remove(button2); } base.FormBorderStyle = value; } } #region 隐藏父类的属性,使其不可见 [Browsable(false)] public new string Text { get { return titlelabel.Text; } set { } } [Browsable(false)] public new bool ControlBox { get { return false; } set { base.ControlBox = false; } } #endregion [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] [Description("窗体标题")] public string Title { get { return titlelabel.Text; } set { titlelabel.Text = value; } } [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] [Description("窗体标题字体样式")] public Font TitleFont { get { return titlelabel.Font; } set { titlelabel.Font = value; } } [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] [Description("窗体标题字体颜色")] public Color TitleColor { get { return titlelabel.ForeColor; } set { titlelabel.ForeColor = value; } } [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] [Description("窗体标题栏背景色")] public Color TitleBarBackColor { get { return titlepanel.BackColor; } set { titlepanel.BackColor = value; } } public new bool MaximizeBox { get { return titlepanel.Contains(button2); } set { if (!value) { titlepanel.Controls.Remove(button2); } else if (!titlepanel.Contains(button2)) { titlepanel.Controls.Add(button2); } } } public new bool MinimizeBox { get { return titlepanel.Contains(button3); } set { if (!value) { titlepanel.Controls.Remove(button3); } else if (!titlepanel.Contains(button3)) { titlepanel.Controls.Add(button3); } } } private void ResetTitlePanel() { base.ControlBox = false; base.Text = null; SetToolTip(button1, "关闭"); button2.Size = button1.Size; SetToolTip(button2, "最大化或还原"); button3.Size = button1.Size; SetToolTip(button3, "最小化"); } private void SetToolTip(Control ctrl, string tip) { new ToolTip().SetToolTip(ctrl, tip); } public ZForm() { InitializeComponent(); ResetTitlePanel(); } private void Titlebutton_Click(object sender, EventArgs e) { Button btn = (Button)sender; switch (btn.Tag.ToString()) { case "close": { this.Close(); break; } case "max": { if (this.WindowState == FormWindowState.Maximized) { this.WindowState = FormWindowState.Normal; } else { this.WindowState = FormWindowState.Maximized; } break; } case "min": { if (this.WindowState != FormWindowState.Minimized) { this.WindowState = FormWindowState.Minimized; } break; } } } private void Titlepanel_MouseDown(object sender, MouseEventArgs e) { if (this.WindowState == FormWindowState.Maximized) { return; } //Titlepanel.Cursor = Cursors.NoMove2D; oldMousePosition = e.Location; moving = true; } private void Titlepanel_MouseUp(object sender, MouseEventArgs e) { //Titlepanel.Cursor = Cursors.Default; moving = false; } private void Titlepanel_MouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left && moving) { Point newPosition = new Point(e.Location.X - oldMousePosition.X, e.Location.Y - oldMousePosition.Y); this.Location += new Size(newPosition); } } private void Titlepanel_DoubleClick(object sender, EventArgs e) { if (titlepanel.Contains(button2)) { button2.PerformClick(); } } private void titlepanel_ControlRemoved(object sender, ControlEventArgs e) { switch (e.Control.Name) { case "button2": { if (titlepanel.Contains(button3)) { button3.Left = button1.Left - button1.Width; } break; } } } private void titlepanel_ControlAdded(object sender, ControlEventArgs e) { switch (e.Control.Name) { case "button2": { if (titlepanel.Contains(button3)) { button3.Left = button2.Left - button2.Width; } break; } case "button3": { if (titlepanel.Contains(button2)) { button3.Left = button2.Left - button2.Width; } break; } } } }
[★] VS2005[C#] 操作 Excel 全攻略 ZT
[★] VS2005[C#] 操作 Excel 全攻略[@more@]using System;using System.Collections.Generic;using System.ComponentModel;using...
198个经典C#WinForm实例源码
198个经典C#WinForm实例源码 1、窗体 2、控件 3、图像 4、报表 5、系统 6、文件 7、网络 8、数据库 9、加密、解密 10、硬件读写
1490



被折叠的 条评论
为什么被折叠?



