代码语言
.
CSharp
.
JS
Java
Asp.Net
C
MSSQL
PHP
Css
PLSQL
Python
Shell
EBS
ASP
Perl
ObjC
VB.Net
VBS
MYSQL
GO
Delphi
AS
DB2
Domino
Rails
ActionScript
Scala
代码分类
文件
系统
字符串
数据库
网络相关
图形/GUI
多媒体
算法
游戏
Jquery
Extjs
Android
HTML5
菜单
网页交互
WinForm
控件
企业应用
安全与加密
脚本/批处理
开放平台
其它
【
CSharp
】
导入导出excel(.xls,.xlsx)
作者:
玉云
/ 发布于
2014/10/22
/
817
#region 导入导出excel private SaveFileDialog SaveDialog; private OpenFileDialog OpenDialog; private Thread InvokeThread; private DialogResult InvokeResult; bool issave = false; private void Invoker() { if (issave) SaveDialog = new SaveFileDialog(); else OpenDialog = new OpenFileDialog(); InvokeThread = new Thread(new ThreadStart(InvokeMethod)); InvokeThread.SetApartmentState(ApartmentState.STA); InvokeResult = DialogResult.None; } private DialogResult InvokeDialogResult() { InvokeThread.Start(); InvokeThread.Join(); return InvokeResult; } private void InvokeMethod() { if (issave) InvokeResult = SaveDialog.ShowDialog(); else InvokeResult = OpenDialog.ShowDialog(); } /// <summary> /// //excel 导入datatable /// </summary> /// <param name="bn">导入按钮</param> /// <param name="process">当前操作进度信息</param> /// <param name="error">错误信息</param> /// <returns></returns> public System.Data.DataTable ImportExcel(System.Windows.Forms.Button bn, System.Windows.Forms.TextBox process, System.Windows.Forms.TextBox error) { process.Text = ""; error.Text = ""; bn.Enabled = false; issave = false; Invoker(); OpenDialog.Filter = "Excel(2000-2007) (*.xls)|*.xls|Excel(2010) (*.xlsx)|*.xlsx"; OpenDialog.FilterIndex = 0; OpenDialog.RestoreDirectory = true; //OpenDialog.Title = "导入文件路径"; System.Data.DataTable dt = null; if (InvokeDialogResult() == DialogResult.OK) { string strName = OpenDialog.FileName; string strcon = ""; try { FileInfo file = new FileInfo(strName); if (!file.Exists) { error.Text = GetErrorMSG("D0014", ""); return null; } string extension = file.Extension; //不同版本的连接字符串 switch (extension) { case ".xls": //strcon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'"; //break; case ".xlsx": strcon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'"; break; default: strcon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'"; break; } OleDbConnection olecon = new OleDbConnection(strcon); olecon.Open(); //返回Excel的架构,包括各个sheet表的名称等 System.Data.DataTable dtSheetName = olecon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); string[] strTableNames = new string[dtSheetName.Rows.Count]; for (int k = 0; k < dtSheetName.Rows.Count; k++) { strTableNames[k] = dtSheetName.Rows[k]["TABLE_NAME"].ToString(); OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [" + strTableNames[k] + "]", strcon); dt = new System.Data.DataTable(); da.Fill(dt); if (dt.Rows.Count != 0) { bn.Enabled = true; olecon.Close(); return dt; } } } catch (Exception ex) { bn.Enabled = true; error.Text = ex.Message; } } bn.Enabled = true; return dt; } /// <summary> /// DataGridView 导出到Excel /// </summary> /// <param name="bn">导出按钮</param> /// <param name="gridView"></param> /// <param name="process">当前操作进度信息</param> /// <param name="error">错误信息</param> /// <param name="sheetname">sheet名称</param> public void ExportToExcel(System.Windows.Forms.Button bn, DataGridView gridView, System.Windows.Forms.TextBox process, System.Windows.Forms.TextBox error, string sheetname) { //导出到execl try { process.Text = ""; error.Text = ""; issave = true; Invoker(); SaveDialog.Filter = "Excel(2000-2007) (*.xls)|*.xls|Excel(2010) (*.xlsx)|*.xlsx"; SaveDialog.FilterIndex = 0; SaveDialog.RestoreDirectory = true; SaveDialog.Title = "导出文件保存路径"; if (InvokeDialogResult() == DialogResult.OK) { bn.Enabled = false; string strName = SaveDialog.FileName; if (strName.Length != 0) { //没有数据的话就不往下执行 if (gridView.Rows.Count == 0) { bn.Enabled = true; error.Text = GetErrorMSG("D0015", ""); return; } //ProgressBar toolStripProgressBar1=new ProgressBar(); //toolStripProgressBar1.Visible = true; System.Reflection.Missing miss = System.Reflection.Missing.Value; Microsoft.Office.Interop.Excel.ApplicationClass excel = new Microsoft.Office.Interop.Excel.ApplicationClass(); excel.Application.Workbooks.Add(true); ; excel.Visible = false;//若是true,则在导出的时候会显示EXcel界面。 excel.SheetsInNewWorkbook = 1;//只有一个sheet if (excel == null) { bn.Enabled = true; error.Text = GetErrorMSG("D0016", ""); return; } Microsoft.Office.Interop.Excel.Workbooks books = (Microsoft.Office.Interop.Excel.Workbooks)excel.Workbooks; Microsoft.Office.Interop.Excel.Workbook book = (Microsoft.Office.Interop.Excel.Workbook)(books.Add(miss)); Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)book.ActiveSheet; sheet.Name = sheetname; System.Data.DataTable dt = new System.Data.DataTable(); for (int i = 0; i < gridView.Columns.Count; i++) { //if (gridView.Columns[i].Name == "cb" || !gridView.Columns[i].Visible) //{ // gridView.Columns.Remove(gridView.Columns[i]); // i--; //} if (gridView.Columns[i].Name != "cb" && gridView.Columns[i].Visible) { dt.Columns.Add(gridView.Columns[i].HeaderText); } } for (int i = 0; i < gridView.Rows.Count; i++) { System.Data.DataRow dr = dt.NewRow(); for (int j = 0; j < dt.Columns.Count; j++) { if (gridView.Rows[i].Cells[dt.Columns[j].Caption].Value.GetType() == typeof(string)) { dr[j] = "'" + Functions.GetStringValue(gridView.Rows[i].Cells[dt.Columns[j].Caption].Value); } else if (gridView.Rows[i].Cells[dt.Columns[j].Caption].Value.GetType() == typeof(DateTime)) { dr[j] = "'" + Convert.ToDateTime(gridView.Rows[i].Cells[dt.Columns[j].Caption].Value).ToString("yyyy/MM/dd HH:mm"); } else { dr[j] = Functions.GetStringValue(gridView.Rows[i].Cells[dt.Columns[j].Caption].Value); } } dt.Rows.Add(dr); } //生成列名称 //for (int i = 0; i < gridView.Columns.Count; i++) //{ // excel.Cells[1, i + 1] = gridView.Columns[i].HeaderText; //} for (int i = 0; i < dt.Columns.Count; i++) { excel.Cells[1, i + 1] = dt.Columns[i].Caption; } float percent = 0; int count = 0; for (int i = 0; i < dt.Rows.Count; i++) { for (int j = 0; j < dt.Columns.Count; j++) { //if (dt.Rows[i][j].GetType() == typeof(string)) //{ // excel.Cells[i + 2, j + 1] = "'" + dt.Rows[i][j].ToString(); //} //else if (dt.Rows[i][j].GetType() == typeof(DateTime)) //{ // excel.Cells[i + 2, j + 1] = "'" + Convert.ToDateTime(dt.Rows[i][j]).ToString("yyyy/MM/dd HH:mm"); //} //else //{ excel.Cells[i + 2, j + 1] = Functions.GetStringValue(dt.Rows[i][j]); //} //自动换行 //excel.get_Range(excel.Cells[i + 2, j + 1], excel.Cells[j + 1, j + 1]).Columns.WrapText = true; //自动加行高 //excel.get_Range(excel.Cells[i + 2, j + 1], excel.Cells[i + 2, j + 1]).Rows.AutoFit(); //System.Windows.Forms.Application.DoEvents(); } //toolStripProgressBar1.Value += 100 / gridView.RowCount; count++; percent = ((float)(100 * count)) / dt.Rows.Count; process.Text = GetErrorMSG("D0017", "") + "[" + percent.ToString("0.00") + "%]..."; } //填充数据 //for (int i = 0; i < gridView.Rows.Count; i++) //{ // for (int j = 0; j < gridView.Columns.Count; j++) // { // if (gridView[j, i].Value.GetType() == typeof(string)) // { // excel.Cells[i + 2, j + 1] = "'" + gridView[j, i].Value.ToString(); // } // else if (gridView[j, i].Value.GetType() == typeof(DateTime)) // { // excel.Cells[i + 2, j + 1] = "'" + Convert.ToDateTime(gridView[j, i].Value).ToString("yyyy/MM/dd HH:mm"); // } // else // { // excel.Cells[i + 2, j + 1] = gridView[j, i].Value.ToString(); // } // //自动换行 // //excel.get_Range(excel.Cells[i + 2, j + 1], excel.Cells[j + 1, j + 1]).Columns.WrapText = true; // //自动加行高 // //excel.get_Range(excel.Cells[i + 2, j + 1], excel.Cells[i + 2, j + 1]).Rows.AutoFit(); // //System.Windows.Forms.Application.DoEvents(); // } // //toolStripProgressBar1.Value += 100 / gridView.RowCount; // count++; // percent = ((float)(100 * count)) / gridView.Rows.Count; // process.Text = GetErrorMSG("D0017", "") + "[" + percent.ToString("0.00") + "%]..."; //} sheet.SaveAs(strName, miss, miss, miss, miss, miss, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, miss, miss, miss); book.Close(false, miss, miss); books.Close(); excel.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet); System.Runtime.InteropServices.Marshal.ReleaseComObject(book); System.Runtime.InteropServices.Marshal.ReleaseComObject(books); System.Runtime.InteropServices.Marshal.ReleaseComObject(excel); bn.Enabled = true; GC.Collect(); process.Text = GetErrorMSG("D0018", ""); //toolStripProgressBar1.Value = 0; //toolStripProgressBar1.Visible = false; System.Diagnostics.Process.Start(strName); } } } catch (Exception ex) { error.Text = ex.Message; bn.Enabled = true; } } /// <summary> /// datatable 导出到Excel /// </summary> /// <param name="bn">导出按钮</param> /// <param name="gridView"></param> /// <param name="process">当前操作进度信息</param> /// <param name="error">错误信息</param> /// <param name="sheetname">sheet名称</param> public void DataTableToExcel(System.Windows.Forms.Button bn, System.Data.DataTable dt, System.Windows.Forms.TextBox process, System.Windows.Forms.TextBox error, string sheetname) { //导出到execl try { process.Text = ""; error.Text = ""; issave = true; Invoker(); SaveDialog.Filter = "Excel(2000-2007) (*.xls)|*.xls|Excel(2010) (*.xlsx)|*.xlsx"; SaveDialog.FilterIndex = 0; SaveDialog.RestoreDirectory = true; SaveDialog.Title = "导出文件保存路径"; if (InvokeDialogResult() == DialogResult.OK) { bn.Enabled = false; string strName = SaveDialog.FileName; if (strName.Length != 0) { //没有数据的话就不往下执行 if (dt.Rows.Count == 0) { bn.Enabled = true; error.Text = GetErrorMSG("D0015", ""); return; } System.Reflection.Missing miss = System.Reflection.Missing.Value; Microsoft.Office.Interop.Excel.ApplicationClass excel = new Microsoft.Office.Interop.Excel.ApplicationClass(); excel.Application.Workbooks.Add(true); ; excel.Visible = false;//若是true,则在导出的时候会显示EXcel界面。 excel.SheetsInNewWorkbook = 1;//只有一个sheet if (excel == null) { bn.Enabled = true; error.Text = GetErrorMSG("D0016", ""); return; } Microsoft.Office.Interop.Excel.Workbooks books = (Microsoft.Office.Interop.Excel.Workbooks)excel.Workbooks; Microsoft.Office.Interop.Excel.Workbook book = (Microsoft.Office.Interop.Excel.Workbook)(books.Add(miss)); Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)book.ActiveSheet; sheet.Name = sheetname; //生成列名称 for (int i = 0; i < dt.Columns.Count; i++) { excel.Cells[1, i + 1] = dt.Columns[i].Caption; } float percent = 0; int count = 0; for (int i = 0; i < dt.Rows.Count; i++) { for (int j = 0; j < dt.Columns.Count; j++) { excel.Cells[i + 2, j + 1] = Functions.IsNull(dt.Rows[i][j]) ? "" : "'" + dt.Rows[i][j].ToString(); } count++; percent = ((float)(100 * count)) / dt.Rows.Count; process.Text = GetErrorMSG("D0017", "") + "[" + percent.ToString("0.00") + "%]..."; } sheet.SaveAs(strName, miss, miss, miss, miss, miss, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, miss, miss, miss); book.Close(false, miss, miss); books.Close(); excel.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet); System.Runtime.InteropServices.Marshal.ReleaseComObject(book); System.Runtime.InteropServices.Marshal.ReleaseComObject(books); System.Runtime.InteropServices.Marshal.ReleaseComObject(excel); bn.Enabled = true; GC.Collect(); process.Text = GetErrorMSG("D0018", ""); System.Diagnostics.Process.Start(strName); } } } catch (Exception ex) { error.Text = ex.Message; bn.Enabled = true; } } /// <summary> /// datatable 导出到Excel (excel模板导出) /// </summary> /// <param name="bn">导出按钮</param> /// <param name="gridView"></param> /// <param name="process">当前操作进度信息</param> /// <param name="error">错误信息</param> /// <param name="sheetname">sheet名称</param> public void CLToExcel(System.Windows.Forms.Button bn, System.Data.DataTable dt, System.Windows.Forms.TextBox process, System.Windows.Forms.TextBox error, string sheetname,string date) { //导出到execl try { process.Text = ""; error.Text = ""; //调用的模板文件 string path = ""; #if DEBUG path = @"..\..\Data\材料导出.xlsx"; #else path=Application.StartupPath + @"\Data\材料导出.xlsx"; #endif FileInfo mode = new FileInfo(path); Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application(); if (app == null) { return; } app.Application.DisplayAlerts = false; app.Visible = false; if (mode.Exists) { Microsoft.Office.Interop.Excel.Workbook tworkbook; Object missing = System.Reflection.Missing.Value; app.Workbooks.Add(missing); //调用模板 tworkbook = app.Workbooks.Open(mode.FullName, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing); Microsoft.Office.Interop.Excel.Worksheet tworksheet = (Microsoft.Office.Interop.Excel.Worksheet)tworkbook.Sheets[1]; DateTime time = Convert.ToDateTime(date); //配置文件中显示的日期数 int defaultday = Functions.GetInt(GetNode("/configuration/DayOfWeek/day")); for (int i = 0; i < defaultday; i++) { tworksheet.Cells[1, i + 7] = time.AddDays(i); } for (int i = 0; i < dt.Rows.Count; i++) { tworksheet.Cells[i + 3, 1] = "'" + Functions.GetStringValue(dt.Rows[i][0]); tworksheet.Cells[i + 3, 2] = "'" + Functions.GetStringValue(dt.Rows[i][1]); tworksheet.Cells[i + 3, 7] = "'" + Functions.GetStringValue(dt.Rows[i][2]); } issave = true; Invoker(); SaveDialog.Filter = "Excel(2000-2007) (*.xls)|*.xls|Excel(2010) (*.xlsx)|*.xlsx"; SaveDialog.FilterIndex = 0; SaveDialog.RestoreDirectory = true; SaveDialog.Title = "导出文件保存路径"; if (InvokeDialogResult() == DialogResult.OK) { bn.Enabled = false; string strName = SaveDialog.FileName; if (strName.Length != 0) { tworksheet.SaveAs(strName, missing, missing, missing, missing, missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, missing, missing, missing); tworkbook.Close(false, mode.FullName, missing); app.Workbooks.Close(); app.Quit(); bn.Enabled = true; tworkbook = null; app = null; GC.Collect(); process.Text = GetErrorMSG("D0018", ""); System.Diagnostics.Process.Start(strName); } } } } catch (Exception ex) { error.Text = ex.Message; bn.Enabled = true; } } #endregion
试试其它关键字
同语言下
.
文件IO 操作类库
.
Check图片类型[JPEG(.jpg 、.jpeg),TIF,GIF,BMP,PNG,P
.
机器名和IP取得(IPV4 IPV6)
.
Tiff转换Bitmap
.
linqHelper
.
MadieHelper.cs
.
RegHelper.cs
.
如果关闭一个窗体后激活另一个窗体的事件或方法
.
创建日志通用类
.
串口辅助开发类
可能有用的
.
文件IO 操作类库
.
Check图片类型[JPEG(.jpg 、.jpeg),TIF,GIF,BMP,PNG,P
.
机器名和IP取得(IPV4 IPV6)
.
Tiff转换Bitmap
.
linqHelper
.
MadieHelper.cs
.
RegHelper.cs
.
如果关闭一个窗体后激活另一个窗体的事件或方法
.
创建日志通用类
.
串口辅助开发类
玉云
贡献的其它代码
(
22
)
.
android 通过Build获取手机硬件信息
.
判断checkboxlist 是否选中的js函数
.
获取每一条查询语句的记录数
.
精确计算工具类,提供加减乘除的计算
.
JavaBean和Map转换封装类
.
将文件夹下的所有properties文件转换成map
.
浏览器兼容 copyToClipboard("拷贝内容")
.
android写联系人信息的方法
.
显示内容太多用...显示的SQL语句
.
删除SQL表中所有数据 Truncate
Copyright © 2004 - 2024 dezai.cn. All Rights Reserved
站长博客
粤ICP备13059550号-3