winform应用使用DataGridView数据导出到Excel
将DataGridView中的数据导出至Excel中(亲测成功)

将DataGridView中的数据导出至Excel(亲测成功)一、建立一个静态方法public static void ExportAsExcel(DataGridView dgv){OutputAsExcelFile(DGVHelper.DataGridViewToTable(dgv));}二、把DataGridView中的数据转换到DataTable中///<summary>///将DataGridView中的数据转换为DataTable包含隐藏列///</summary>///<param name="dgv"></param>///<returns></returns>public static DataTable DataGridViewToTable(DataGridView dgv){DataTable dt=new DataTable();//循环列标题名称,处理了隐藏的行不显示for(int count=0;count<dgv.Columns.Count;count++){if(dgv.Columns[count].Visible==true){dt.Columns.Add(dgv.Columns[count].HeaderText.ToString());}}//循环行,处理了隐藏的行不显示for(int count=0;count<dgv.Rows.Count;count++){DataRow dr=dt.NewRow();int curr=0;for(int countsub=0;countsub<dgv.Columns.Count;countsub++){if(dgv.Columns[countsub].Visible==true){if(dgv.Rows[count].Cells[countsub].Value!=null){dr[curr]=dgv.Rows[count].Cells[countsub].Value.ToString();}else{dr[curr]="";}curr++;}}dt.Rows.Add(dr);}return dt;}三、把DataTable中的数据导出到Excel中public static void OutputAsExcelFile(DataTable dt){if(dt.Rows.Count<=0){MessM.PromptInfo("提示","无数据!");return;}SaveFileDialog s=new SaveFileDialog{Title="保存Excel文件",Filter="Excel文件(*.xls)|*.xls",FilterIndex=1};if(s.ShowDialog()==DialogResult.OK)filePath=s.FileName;elsereturn;DTExportToExcel(dt);}///<summary>///第二步:导出dataTable到Excel///</summary>///<param name="dt"></param>private static void DTExportToExcel(DataTable dt){//第二步:导出dataTable到Excellong rowNum=dt.Rows.Count;//行数int columnNum=dt.Columns.Count;//列数Excel.Application m_xlApp=new Excel.Application{DisplayAlerts=false,//不显示更改提示Visible=false};Excel.Workbooks workbooks=m_xlApp.Workbooks;Excel.Workbook workbook=workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);Excel.Worksheet worksheet=(Excel.Worksheet)workbook.Worksheets[1];//取得sheet1try{string[,]datas=new string[rowNum+1,columnNum];for(int i=0;i<columnNum;i++)//写入字段datas[0,i]=dt.Columns[i].Caption;//Excel.Range range=worksheet.get_Range(worksheet.Cells[1,1],worksheet.Cells[1, columnNum]);Excel.Range range=m_xlApp.Range[worksheet.Cells[1,1],worksheet.Cells[1, columnNum]];range.Interior.ColorIndex=15;//15代表灰色range.Font.Bold=true;range.Font.Size=10;int r=0;for(r=0;r<rowNum;r++){for(int i=0;i<columnNum;i++){object obj=dt.Rows[r][dt.Columns[i].ToString()];datas[r+1,i]=obj==null?"":"'"+obj.ToString().Trim();//在obj.ToString()前加单引號是为了防止自己主动转化格式}Application.DoEvents();//加入进度条}//Excel.Range fchR=worksheet.get_Range(worksheet.Cells[1,1], worksheet.Cells[rowNum+1,columnNum]);Excel.Range fchR=m_xlApp.Range[worksheet.Cells[1,1],worksheet.Cells[rowNum+1, columnNum]];fchR.Value2=datas;worksheet.Columns.EntireColumn.AutoFit();//列宽自适应。
C#将DataGridView中显示的数据导出到Excel(.xls和.xlsx格式)—NPOI

C#将DataGridView中显⽰的数据导出到Excel(.xls和.xlsx格式)—NPOI 前⾔ 本地数据库表中有46785条数据,测试正常 初次运⾏程序第⼀次导出,⽤时在4-5s左右;此后再导出⽤时在2-3s左右;可能与缓存有关 ⽀持导出为.xls和.xlsx格式 可以⾃定义字体和字号 exe测试⽂件下载地址: 密码:test实现步骤⼀、安装NPOI右键项⽬→ "管理NuGet程序包" →搜索NPOI →安装⼆、创建类using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;using erModel;using erModel;//导出xls格式⽤HSSFusing erModel;//导出xlsx格式⽤XSSFusing System.IO;using System.Runtime.InteropServices;using System.Diagnostics;using NPOI.SS.Util;namespace ExportToExcel{public class ExportDgvToExcel{#region NPOI DataGridView 导出 EXCEL/// <summary>/// NPOI DataGridView 导出 EXCEL/// 03版Excel-xls最⼤⾏数是65536⾏,最⼤列数是256列/// 07版Excel-xlsx最⼤⾏数是1048576⾏,最⼤列数是16384列/// </summary>/// <param name="fileName">默认保存⽂件名</param>/// <param name="dgv">DataGridView</param>/// <param name="fontname">字体名称</param>/// <param name="fontsize">字体⼤⼩</param>public void ExportExcel(string fileName, DataGridView dgv, string fontname, short fontsize){IWorkbook workbook;ISheet sheet;Stopwatch sw = null;//判断datagridview中内容是否为空if (dgv.Rows.Count == 0){MessageBox.Show("DataGridView中内容为空,请先导⼊数据!", "提⽰", MessageBoxButtons.OK, MessageBoxIcon.Warning); return;}//保存⽂件string saveFileName = "";SaveFileDialog saveFileDialog = new SaveFileDialog();saveFileDialog.DefaultExt = "xls";saveFileDialog.Filter = "Excel⽂件(*.xls)|*.xls|Excel⽂件(*.xlsx)|*.xlsx";saveFileDialog.RestoreDirectory = true;saveFileDialog.Title = "Excel⽂件保存路径";saveFileDialog.FileName = fileName;MemoryStream ms = new MemoryStream(); //MemoryStreamif (saveFileDialog.ShowDialog() == DialogResult.OK)//**程序开始计时**//sw = new Stopwatch();sw.Start();saveFileName = saveFileDialog.FileName;//检测⽂件是否被占⽤if (!CheckFiles(saveFileName)){MessageBox.Show("⽂件被占⽤,请关闭⽂件" + saveFileName);workbook = null;ms.Close();ms.Dispose();return;}}else{workbook = null;ms.Close();ms.Dispose();}//*** 根据扩展名xls和xlsx来创建对象string fileExt = Path.GetExtension(saveFileName).ToLower();if (fileExt == ".xlsx"){workbook = new XSSFWorkbook();}else if (fileExt == ".xls"){workbook = new HSSFWorkbook();}else{workbook = null;}//***//创建Sheetif (workbook != null){sheet = workbook.CreateSheet("Sheet1");//Sheet的名称}else{return;}//设置单元格样式ICellStyle cellStyle = workbook.CreateCellStyle();//⽔平居中对齐和垂直居中对齐cellStyle.Alignment = erModel.HorizontalAlignment.Center;cellStyle.VerticalAlignment = erModel.VerticalAlignment.Center;//设置字体IFont font = workbook.CreateFont();font.FontName = fontname;//字体名称font.FontHeightInPoints = fontsize;//字号font.Color = NPOI.HSSF.Util.HSSFColor.Black.Index;//字体颜⾊cellStyle.SetFont(font);//添加列名IRow headRow = sheet.CreateRow(0);for (int i = 0; i < dgv.Columns.Count; i++){//隐藏⾏列不导出if (dgv.Columns[i].Visible == true){headRow.CreateCell(i).SetCellValue(dgv.Columns[i].HeaderText);headRow.GetCell(i).CellStyle = cellStyle;}}//根据类型写⼊内容for (int rowNum = 0; rowNum < dgv.Rows.Count; rowNum++){///跳过第⼀⾏,第⼀⾏为列名IRow dataRow = sheet.CreateRow(rowNum + 1);for (int columnNum = 0; columnNum < dgv.Columns.Count; columnNum++){int columnWidth = sheet.GetColumnWidth(columnNum) / 256; //列宽//隐藏⾏列不导出if (dgv.Rows[rowNum].Visible == true && dgv.Columns[columnNum].Visible == true) {//防⽌⾏列超出Excel限制if (fileExt == ".xls"){//03版Excel最⼤⾏数是65536⾏,最⼤列数是256列if (rowNum > 65536){MessageBox.Show("⾏数超过Excel限制!");return;}if (columnNum > 256){MessageBox.Show("列数超过Excel限制!");return;}}else if (fileExt == ".xlsx"){//07版Excel最⼤⾏数是1048576⾏,最⼤列数是16384列if (rowNum > 1048576)MessageBox.Show("⾏数超过Excel限制!");return;}if (columnNum > 16384){MessageBox.Show("列数超过Excel限制!");return;}}ICell cell = dataRow.CreateCell(columnNum);if (dgv.Rows[rowNum].Cells[columnNum].Value == null){cell.SetCellType(CellType.Blank);}else{if (dgv.Rows[rowNum].Cells[columnNum].ValueType.FullName.Contains("System.Int32")){cell.SetCellValue(Convert.ToInt32(dgv.Rows[rowNum].Cells[columnNum].Value));}else if (dgv.Rows[rowNum].Cells[columnNum].ValueType.FullName.Contains("System.String")){cell.SetCellValue(dgv.Rows[rowNum].Cells[columnNum].Value.ToString());}else if (dgv.Rows[rowNum].Cells[columnNum].ValueType.FullName.Contains("System.Single")){cell.SetCellValue(Convert.ToSingle(dgv.Rows[rowNum].Cells[columnNum].Value));}else if (dgv.Rows[rowNum].Cells[columnNum].ValueType.FullName.Contains("System.Double")){cell.SetCellValue(Convert.ToDouble(dgv.Rows[rowNum].Cells[columnNum].Value));}else if (dgv.Rows[rowNum].Cells[columnNum].ValueType.FullName.Contains("System.Decimal")){cell.SetCellValue(Convert.ToDouble(dgv.Rows[rowNum].Cells[columnNum].Value));}else if (dgv.Rows[rowNum].Cells[columnNum].ValueType.FullName.Contains("System.DateTime")){cell.SetCellValue(Convert.ToDateTime(dgv.Rows[rowNum].Cells[columnNum].Value).ToString("yyyy-MM-dd"));}else if (dgv.Rows[rowNum].Cells[columnNum].ValueType.FullName.Contains("System.DBNull")){cell.SetCellValue("");}}//设置列宽IRow currentRow;if (sheet.GetRow(rowNum) == null){currentRow = sheet.CreateRow(rowNum);}else{currentRow = sheet.GetRow(rowNum);}if (currentRow.GetCell(columnNum) != null){ICell currentCell = currentRow.GetCell(columnNum);int length = Encoding.Default.GetBytes(currentCell.ToString()).Length;if (columnWidth < length){columnWidth = length + 10; //设置列宽数值}}sheet.SetColumnWidth(columnNum, columnWidth * 256);//单元格样式dataRow.GetCell(columnNum).CellStyle = cellStyle;}}}//保存为Excel⽂件workbook.Write(ms);FileStream file = new FileStream(saveFileName, FileMode.Create);workbook.Write(file);file.Close();workbook = null;ms.Close();ms.Dispose();//**程序结束计时**//sw.Stop();double totalTime = sw.ElapsedMilliseconds / 1000.0;MessageBox.Show(fileName + " 导出成功\n耗时" + totalTime + "s", "提⽰", MessageBoxButtons.OK, rmation); }#endregion#region 检测⽂件是否被占⽤/// <summary>/// 判定⽂件是否打开/// </summary>[DllImport("kernel32.dll")]public static extern IntPtr _lopen(string lpPathName, int iReadWrite);[DllImport("kernel32.dll")]public static extern bool CloseHandle(IntPtr hObject);public const int OF_READWRITE = 2;public const int OF_SHARE_DENY_NONE = 0x40;public readonly IntPtr HFILE_ERROR = new IntPtr(-1);/// <summary>/// 检测⽂件被占⽤/// </summary>/// <param name="FileNames">要检测的⽂件路径</param>/// <returns></returns>public bool CheckFiles(string FileNames){if (!File.Exists(FileNames)){//⽂件不存在return true;}IntPtr vHandle = _lopen(FileNames, OF_READWRITE | OF_SHARE_DENY_NONE); if (vHandle == HFILE_ERROR){//⽂件被占⽤return false;}//⽂件没被占⽤CloseHandle(vHandle);return true;}#endregion}}三、调⽤private void btnExport_Click_1(object sender, EventArgs e){ExportDgvToExcel export = new ExportDgvToExcel();export.ExportExcel("", dgv, "宋体", 11);//默认⽂件名,DataGridView控件的名称,字体,字号}。
导出DataGridView数据到指定Excel模板

导出DataGridView数据到指定Excel模板string path2 = "C:/Documents and Settings/Administrator/桌面/日返工率.xls";//导出模板文件路径DirectoryInfo dinfo = new DirectoryInfo(path2);string strStart = dateTimePicker1.Value.ToString();UnPercentDal dataDal = new UnPercentDal();DataTable MyDS_Grid = dataDal.GetUnPercentDal(strStart);string FileName = "日返工率";string FileName2 = DateTime.T oday.ToString("yyyyMMdd") + newRandom(/doc/6c1224707.html,lisecon d).Next(10000).T oString();Microsoft.Office.Interop.Excel.Application xApp = newMicrosoft.Office.Interop.Excel.ApplicationClass();xApp.Visible = true;//得到WorkBook对象, 下面的是打开已有的文件Microsoft.Office.Interop.Excel.Workbook xBook = xApp.Workbooks._Open(path2, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);Microsoft.Office.Interop.Excel.Worksheet xSheet =(Microsoft.Office.Interop.Excel.Worksheet)xBook.Sheets[1];foreach (DataRow row in MyDS_Grid.Rows){Microsoft.Office.Interop.Excel.Range rng1 = xSheet.get_Range("A1", Missing.Value);//插入数据到A1行rng1.Value2 = DateTime.Now.ToShortDateString();Microsoft.Office.Interop.Excel.Range rng2 =xSheet.get_Range("A2", Missing.Value);rng2.Value2 = row["OrderCode"].ToString();Microsoft.Office.Interop.Excel.Range rng3 = xSheet.get_Range("A3", Missing.Value);rng3.Value2 = row["SerialNum"].ToString();Microsoft.Office.Interop.Excel.Range rng4 = xSheet.get_Range("A4", Missing.Value);rng4.Value2 = row["MesSort"].T oString();Microsoft.Office.Interop.Excel.Range rng7 = xSheet.get_Range("A7", Missing.Value);rng7.Value2 = row["BrushDate"].ToString();Microsoft.Office.Interop.Excel.Range rng8 = xSheet.get_Range("B6", Missing.Value);rng8.Value2 = row["EmployeeName"].T oString() + "元/m\u00b2";//"m\u00b2"是输出m上标2就是平方米。
把WinForm的DataGridView的数据导出到Excel三种方法

1.#region DataGridView数据显示到Excel2./// <summary>3./// 打开Excel并将DataGridView控件中数据导出到Excel4./// </summary>5./// <param name="dgv">DataGridView对象</param>6./// <param name="isShowExcle">是否显示Excel界面</param>7./// <remarks>8./// add com "Microsoft Excel 11.0 Object Library"9./// using Excel=Microsoft.Office.Interop.Excel;10./// </remarks>11./// <returns> </returns>12.public bool DataGridviewShowToExcel(DataGridView dgv, bool isShowExcle)13.{14.if(dgv.Rows.Count == 0)15.return false;16.//建立Excel对象17.Excel.Application excel = new Excel.Application();18.excel.Application.Workbooks.Add(true);19.excel.Visible = isShowExcle;20.//生成字段名称21.for(int i = 0; i < dgv.ColumnCount; i++)22.{23.excel.Cells[1, i + 1] = dgv.Columns[i].HeaderText;24.}25.//填充数据26.for(int i = 0; i < dgv.RowCount - 1; i++)27.{28.for(int j = 0; j < dgv.ColumnCount; j++)29.{30.if(dgv[j, i].ValueType == typeof(string))31.{32.excel.Cells[i + 2, j + 1] = "'"+ dgv[j, i].Value.ToString();33.}34.else35.{36.excel.Cells[i + 2, j + 1] = dgv[j, i].Value.ToString();38.}39.}40.return true;41.}42.#endregion43.44.#region DateGridView导出到csv格式的Excel45./// <summary>46./// 常用方法,列之间加\t,一行一行输出,此文件其实是csv文件,不过默认可以当成Excel打开。
C#DataGridView导出到Excel

objData[rowIndex, colIndex] = myDataGridView.Rows[rowIndex - 1].Cells[colIndexs[colIndex]].Value.ToString();
}
System.Windows.Forms.Application.DoEvents();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
xlSheet = null;
if (filenameString.Trim() == "") return false;
FileInfo file = new FileInfo(filenameString);
if (file.Exists)
{
try
int rowCount = myDataGridView.RowCount;
List<int> colIndexs = new List<int>();
// 创建缓存数据
object[,] objData = new object[rowCount + 1, dispcolCount];
{
MessageBox.Show("保存出错,请检查!");
return false;
}
finally
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBook.Worksheets);
如何使用c_将Winform下DataGridView中内容导出到Excel

原文地址:转:winform中将datagirdview中数据导出到EXCEL中作者:雪枫如何使用c#将Winform下DataGridView中内容导出到Excel?方法1 :添加dll引用右击选择你所在的项目的“引用”,选择“添加引用”。
弹出“添加引用”对话框。
选择“COM”选项卡。
选择“Microsoft Excel 12.0 Object Library”单击“确定”按钮。
说明:如何发现导入的程序集不能正常工作,可能是由于office安装的缘故,请确保自定义安装office时,选择“.net可编程性支持”:代码:public static bool ExportForDataGridview(DataGridView gridView, string fileName, bool isShowExcle) {//建立Excel对象Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();try{if (app == null){return false;}app.Visible = isShowExcle;Workbooks workbooks = app.Workbooks;_Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);Sheets sheets = workbook.Worksheets;_Worksheet worksheet = (_Worksheet)sheets.get_Item(1);if (worksheet == null){return false;}string sLen = "";//取得最后一列列名char H = (char)(64 + gridView.ColumnCount / 26);char L = (char)(64 + gridView.ColumnCount % 26);if (gridView.ColumnCount < 26){sLen = L.ToString();}else{sLen = H.ToString() + L.ToString();//标题string sTmp = sLen + "1";Range ranCaption = worksheet.get_Range(sTmp, "A1"); string[] asCaption = new string[gridView.ColumnCount]; for (int i = 0; i < gridView.ColumnCount; i++){asCaption[i] = gridView.Columns[i].HeaderText;}ranCaption.Value2 = asCaption;//数据object[] obj = new object[gridView.Columns.Count];for (int r = 0; r < gridView.RowCount - 1; r++){for (int l = 0; l < gridView.Columns.Count; l++){if (gridView[l, r].ValueType == typeof(DateTime)){obj[l] = gridView[l, r].Value.ToString();}else{obj[l] = gridView[l, r].Value;}}string cell1 = sLen + ((int)(r + 2)).ToString();string cell2 = "A" + ((int)(r + 2)).ToString();Range ran = worksheet.get_Range(cell1, cell2);ran.Value2 = obj;}workbook.SaveCopyAs(fileName);workbook.Saved = true;}finally{//关闭erControl = false;app.Quit();}return true;}方法2用流保存成xls文件. 这种方法比较好,不用引用Excel组件. 下面是具体例子,可以参考using System.IO;using System.Text;/// <summary>/// 另存新档按钮/// </summary>private void SaveAs() //另存新档按钮导出成Excel{SaveFileDialog saveFileDialog = new SaveFileDialog();saveFileDialog.Filter = "Execl files (*.xls)|*.xls";saveFileDialog.FilterIndex = 0;saveFileDialog.RestoreDirectory = true;saveFileDialog.CreatePrompt = true;saveFileDialog.Title = "Export Excel File To";saveFileDialog.ShowDialog();Stream myStream;myStream = saveFileDialog.OpenFile();StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0)); string str = "";try{//写标题for (int i = 0; i < dgvAgeWeekSex.ColumnCount; i++){if (i > 0){str += "t";}str += dgvAgeWeekSex.Columns[i].HeaderText;}sw.WriteLine(str);//写内容for (int j = 0; j < dgvAgeWeekSex.Rows.Count; j++){string tempStr = "";for (int k = 0; k < dgvAgeWeekSex.Columns.Count; k++){if (k > 0){tempStr += "t";}tempStr += dgvAgeWeekSex.Rows[j].Cells[k].Value.ToString();}sw.WriteLine(tempStr);}sw.Close();myStream.Close();}catch (Exception e){MessageBox.Show(e.ToString());}finally{sw.Close();myStream.Close();}}C# WinForm下DataGridView导出Excel 的实现1.说明:导出的效率说不上很高,但至少是可以接收的.参考网上很多高效导出Excel的方法,实现到时能够实现的,导出速度也很快,不过缺陷在与不能很好的进行单元格的格式化,比如上图中的"拼音码"字段中的值"000000000012120",在导出后就显示"12120",挺郁闷的!o(∩_∩)o,废话不说了,进入正题.......2.首先添加Excel引用3.实现代码/// <summary>/// DataGridView导出Excel/// </summary>/// <param name="strCaption">Excel文件中的标题</param>/// <param name="myDGV">DataGridView 控件</param>/// <returns>0:成功;1ataGridView中无记录;2:Excel无法启动;9999:异常错误</returns>private int ExportExcel(string strCaption, DataGridView myDGV){int result = 9999;// 列索引,行索引,总列数,总行数int ColIndex = 0;int RowIndex = 0;int ColCount = myDGV.ColumnCount;int RowCount = myDGV.RowCount;if (myDGV.RowCount == 0){result = 1;}// 创建Excel对象Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();if (xlApp == null){result = 2;}try{// 创建Excel工作薄Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true);Microsoft.Office.Interop.Excel.Worksheet xlSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlBook.Worksheets[1];// 设置标题Microsoft.Office.Interop.Excel.Range range = xlSheet.get_Range(xlApp.Cells[1, 1], xlApp.Cells[1, ColCount]); //标题所占的单元格数与DataGridView中的列数相同range.MergeCells = true;xlApp.ActiveCell.FormulaR1C1 = strCaption;xlApp.ActiveCell.Font.Size = 20;xlApp.ActiveCell.Font.Bold = true;xlApp.ActiveCell.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter;// 创建缓存数据object[,] objData = new object[RowCount + 1, ColCount];//获取列标题foreach (DataGridViewColumn col in myDGV.Columns){objData[RowIndex, ColIndex++] = col.HeaderText;}// 获取数据for (RowIndex = 1; RowIndex < RowCount; RowIndex++){for (ColIndex = 0; ColIndex < ColCount; ColIndex++)if (myDGV[ColIndex, RowIndex - 1].ValueType == typeof(string)|| myDGV[ColIndex, RowIndex - 1].ValueType == typeof(DateTime))//这里就是验证DataGridView单元格中的类型,如果是string或是DataTime类型,则在放入缓存时在该内容前加入" ";{objData[RowIndex, ColIndex] = "" + myDGV[ColIndex, RowIndex - 1].Value;}else{objData[RowIndex, ColIndex] = myDGV[ColIndex, RowIndex - 1].Value;}}System.Windows.Forms.Application.DoEvents();}// 写入Excelrange = xlSheet.get_Range(xlApp.Cells[2, 1], xlApp.Cells[RowCount, ColCount]);range.Value2 = objData;//保存xlBook.Saved = true;xlBook.SaveCopyAs("C:\测试" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");//返回值result = 0;}catch (Exception err){result = 9999;}finally{xlApp.Quit();GC.Collect(); //强制回收}return result;}4.调用方法(上图中"生成Excel文件"按钮的onClick事件)private void button4_Click(object sender, EventArgs e){int result = this.ExportExcel("测试", this.dataGridView1); //this.dataGridView1ataGridView控件MessageBox.Show(result.ToString());。
c#中datagridview数据导出到excel源码
private void button5_Click_1(object sender, EventArgs e){//建立Excel对象Excel.Application excel = new Excel.Application();excel.Application.Workbooks.Add(true);//生成字段名称for (int i = 0; i < dataGridView2.ColumnCount; i++){excel.Cells[1,i + 1] = dataGridView2.Columns[i].HeaderText;if (y == 0){y = 1;toolStripStatusLabel6.Text = "数据导入中,请等待!";}}//填充数据for (int i = 0; i < dataGridView2.RowCount - 1; i++){for (int j = 0; j < dataGridView2.ColumnCount; j++){if (dataGridView2[j, i].Value == typeof(string)){excel.Cells[i + 2, j + 1] = "" + dataGridView2[i, j].Value.ToString();}else{excel.Cells[i + 2, j + 1] = dataGridView2[j, i].Value.ToString();}}}excel.Visible = true;}===================================================================[原创]万能,高效-C#导出数据到Excel2008年03月18日星期二下午12:56 class CommanPrint{/// <summary>/// 导出Excel/// 版权所有: 天山寒雪QQ:757015000 MSN: haijun.qin@/// </summary>/// <param name="mydgv">控件DataGridView</param>/// <param name="dic">中英文对照的标题</param>public static void ExportTasks(DataGridView mydgv, Dictionary<string, string> dic) {// 定义要使用的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 range;int dcell = 1;int rowindex = 0; int colindex = 0;int rowcount = mydgv.Rows.Count;int colcount = mydgv.Columns.Count;int dispcolcount = dic.Count;try{//初始化Application 对象excelAppexcelApp = new Microsoft.Office.Interop.Excel.Application();//在工作薄的第一个工作表上创建任务列表workBook = excelApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);ws = (Worksheet)workBook.Worksheets[1];// 命名工作表的名称为 = "Sheet1";//创建缓存Object[,] objdata = new object[rowcount + 1, colcount];//创建标题foreach (string s in dic.Keys){objdata[rowindex, colindex++] = dic[s].ToString();}//获取数据for (int i = 0; i < rowcount; i++){dcell = 0;foreach (string ss in dic.Keys){for (int j = 0; j < colcount; j++){if (mydgv.Columns[j].Name == ss){objdata[i + 1, dcell++] = mydgv.Rows[i].Cells[j].FormattedValue.ToString(); //得到样式之后的值}}}}//写入Excelrange = ws.get_Range(excelApp.Cells[1, 1], excelApp.Cells[rowcount, dispcolcount]); range.Value2 = objdata;System.Windows.Forms.Application.DoEvents();//设置格式excelApp.Cells.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlLeft; //全局左对齐excelApp.Cells.EntireColumn.AutoFit();range = ws.get_Range(excelApp.Cells[1, 1], excelApp.Cells[1, colcount]);range.Font.Bold = true; //标题粗体//显示ExcelexcelApp.Visible = true;}catch (Exception ex){throw ex;}============================================================using System;using System.Collections.Generic;using System.Text;using System.Web.UI.WebControls;using System.Data;using System.Web.UI.HtmlControls;namespace Commonpublic class ExcelHelper{// Excel导出public static void Export(GridView dgExport, DataTable dtData){System.Web.HttpContext curContext = System.Web.HttpContext.Current;// IO用于导出并返回excel文件System.IO.StringWriter strWriter = null;System.Web.UI.HtmlTextWriter htmlWriter = null;if (dtData != null){// 设置编码和附件格式curContext.Response.Clear();curContext.Response.ClearContent();curContext.Response.Buffer = true;curContext.Response.ContentType = "application/vnd.ms-excel";curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-7");curContext.Response.Charset = "GB2312";curContext.Response.AppendHeader("content-disposition", "filename=\"" + System.Web.HttpUtility.UrlEncode(dtData.TableName, System.Text.Encoding.UTF8) + ".xls\"");// 导出excel文件strWriter = new System.IO.StringWriter();htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);HtmlForm frm = new HtmlForm();frm.Attributes["runat"] = "server";frm.Controls.Add(dgExport);dgExport.DataSource = dtData.DefaultView;dgExport.DataBind();// 返回客户端dgExport.RenderControl(htmlWriter);curContext.Response.Write(strWriter.ToString());curContext.Response.End();}}}}。
把WinForm的DataGridView的数据导出到Excel三种方法
把WinForm的DataGridView的数据导出到Excel三种方法导出WinForm的DataGridView数据到Excel有多种方法,下面将详细介绍三种常用的方法:方法一:使用Microsoft.Office.Interop.Excel库这是一种常用的方法,使用Microsoft.Office.Interop.Excel库可以直接操作Excel文件。
首先,需要在项目中添加对Microsoft Office 的引用。
然后,可以按照以下步骤导出数据:1. 创建一个Excel应用程序对象:```csharpusing Excel = Microsoft.Office.Interop.Excel;Excel.Application excelApp = new Excel.Application(;```2.创建一个工作簿对象:```csharpExcel.Workbook workbook =excelApp.Workbooks.Add(Type.Missing);```3.创建一个工作表对象:```csharpExcel.Worksheet worksheet = workbook.ActiveSheet;```4. 将DataGridView中的数据导入到Excel中:```csharpfor (int i = 0; i < dataGridView.Rows.Count; i++)for (int j = 0; j < dataGridView.Columns.Count; j++)worksheet.Cells[i + 1, j + 1] =dataGridView.Rows[i].Cells[j].Value.ToString(;}```5. 保存Excel文件并关闭Excel应用程序:```csharpworkbook.SaveAs("路径\\文件名.xlsx");excelApp.Quit(;```方法二:使用OpenXml库OpenXml是一种用于操作Office文件的开放式标准。
winform中DataGridView的数据实现导出excel
winform中DataGridView的数据实现导出excel 1,窗体设计⾸先需要引⼊程序集:Microsoft.Office.Interop.Excel (如果没有引⽤过的需要右键添加引⽤再搜索就⾏了)实现的⽅法:/// <summary>////// </summary>/// <param name="fileName">⽂件路径</param>/// <param name="myDGV">控件DataGridView</param>private void ExportExcels(string fileName, DataGridView myDGV){string saveFileName = "";SaveFileDialog saveDialog = new SaveFileDialog();saveDialog.DefaultExt = "xls";saveDialog.Filter = "Excel⽂件|*.xls";saveDialog.FileName = fileName;saveDialog.ShowDialog();saveFileName = saveDialog.FileName;if (saveFileName.IndexOf(":") < 0) return; //被点了取消Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();if (xlApp == null){MessageBox.Show("⽆法创建Excel对象,可能您的机⼦未安装Excel");return;}Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.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];//取得sheet1 //写⼊标题for (int i = 0; i < myDGV.ColumnCount; i++){worksheet.Cells[1, i + 1] = myDGV.Columns[i].HeaderText;}//写⼊数值for (int r = 0; r < myDGV.Rows.Count; r++){for (int i = 0; i < myDGV.ColumnCount; i++){worksheet.Cells[r + 2, i + 1] = myDGV.Rows[r].Cells[i].Value;}System.Windows.Forms.Application.DoEvents();}worksheet.Columns.EntireColumn.AutoFit();//列宽⾃适应if (saveFileName != ""){try{workbook.Saved = true;workbook.SaveCopyAs(saveFileName);}catch (Exception ex){MessageBox.Show("导出⽂件时出错,⽂件可能正被打开!\n" + ex.Message);}}xlApp.Quit();GC.Collect();//强⾏销毁MessageBox.Show("⽂件: " + fileName + ".xls 保存成功", "信息提⽰", MessageBoxButtons.OK, rmation); } 点击按钮调⽤private void button1_Click(object sender, EventArgs e){string a = "D:" + "\\KKHMD.xls";ExportExcels(a, dataGridView1);} 完成截图。
C# winform Datagridview导出Excel两个方法
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "导出文件保存路径";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
//strName储存保存EXCEL路径
Microsoft.Office.Interop.Excel.ApplicationClass excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
excel.Application.Workbooks.Add(true); ;
//生成字段名称,逐条写,无效率
for (int i = 0; i < gridView.ColumnCount; i++)
{
/// </summary>
/// <param name="gridView"></param>
/// <param name="saveFileDialog"></param>
public void ToExcel1(DataGridView gridView, SaveFileDialog saveFileDialog)
{
try
{
if (gridView.Rows.Count == 0)
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
winform应用使用DataGridView数据导出到Excel,下面是DataGridView到处到Excel的两种方法,附有第二种的工程代码,最近项目使用到这块,就记下来了,其中第一种效率较第二种较高,但是没有第二种容易设置格式:CodeDateGridView导出到csv格式的Excel#region DateGridView导出到csv格式的Excel/**//// <summary>/// 常用方法,列之间加\t,一行一行输出,此文件其实是csv文件,不过默认可以当成Excel打开。
/// </summary>/// <remarks>/// using System.IO;/// </remarks>/// <param name="dgv"></param>private void DataGridViewToExcel(DataGridView dgv) {SaveFileDialog dlg = new SaveFileDialog();dlg.Filter = "Execl files (*.xls)|*.xls";dlg.FilterIndex = 0;dlg.RestoreDirectory = true;dlg.CreatePrompt = true;dlg.Title = "保存为Excel文件";if (dlg.ShowDialog() == DialogResult.OK){Stream myStream;myStream = dlg.OpenFile();StreamWriter sw = newStreamWriter(myStream,System.Text.Encoding.GetEncoding(-0));string columnTitle = "";try{//写入列标题for (int i = 0; i < dgv.ColumnCount; i++){if (i > 0){columnTitle += "\t";}columnTitle +=dgv.Columns[i].HeaderText;}sw.WriteLine(columnTitle);//写入列内容for (int j = 0; j < dgv.Rows.Count; j++){string columnValue = "";for (int k = 0; k <dgv.Columns.Count; k++){if (k > 0){columnValue += "\t";}if (dgv.Rows[j].Cells[k].Value == null)columnValue += "";elsecolumnValue +=dgv.Rows[j].Cells[k].Value.ToString().Trim();}sw.WriteLine(columnValue);}sw.Close();myStream.Close();}catch (Exception e){MessageBox.Show(e.ToString());}finally{sw.Close();myStream.Close();}}}#endregionDataGridView导出到Excel,有一定的判断性#region DataGridView导出到Excel,有一定的判断性/**//// <summary>///方法,导出DataGridView中的数据到Excel文件/// </summary>/// <remarks>/// add com "Microsoft Excel 0 Object Library"/// using Excel=Microsoft.Office.Interop.Excel;/// using System.Reflection;/// </remarks>/// <param name= "dgv"> DataGridView</param>public static void DataGridViewToExcel(DataGridView dgv){验证可操作性#region 验证可操作性//申明保存对话框SaveFileDialog dlg = new SaveFileDialog();//默然文件后缀dlg.DefaultExt = "xls ";//文件后缀列表dlg.Filter = "EXCEL文件(*.XLS)|*.xls ";//默然路径是系统当前路径dlg.InitialDirectory =Directory.GetCurrentDirectory();//打开保存对话框if (dlg.ShowDialog() == DialogResult.Cancel) return;//返回文件路径string fileNameString = dlg.FileName;//验证strFileName是否为空或值无效if (fileNameString.Trim() == " "){ return; }//定义表格内数据的行数和列数int rowscount = dgv.Rows.Count;int colscount = dgv.Columns.Count;//行数必须大于0if (rowscount <= 0){MessageBox.Show("没有数据可供保存", "提示", MessageBoxButtons.OK,rmation);return;}//列数必须大于0if (colscount <= 0){MessageBox.Show("没有数据可供保存", "提示", MessageBoxButtons.OK,rmation);return;}//行数不可以大于65536if (rowscount > 65536){MessageBox.Show("数据记录数太多(最多不能超过65536条),不能保存", "提示", MessageBoxButtons.OK, rmation);return;}//列数不可以大于255if (colscount > 255){MessageBox.Show("数据记录行数太多,不能保存", "提示", MessageBoxButtons.OK,rmation);return;}//验证以fileNameString命名的文件是否存在,如果存在删除它FileInfo file = new FileInfo(fileNameString);if (file.Exists){try{file.Delete();}catch (Exception error){MessageBox.Show(error.Message, "删除失败", MessageBoxButtons.OK,MessageBoxIcon.Warning);return;}}#endregionExcel.Application objExcel = null;Excel.Workbook objWorkbook = null;Excel.Worksheet objsheet = null;try{//申明对象objExcel = newMicrosoft.Office.Interop.Excel.Application();objWorkbook =objExcel.Workbooks.Add(Missing.Value);objsheet =(Excel.Worksheet)objWorkbook.ActiveSheet;//设置EXCEL不可见objExcel.Visible = false;//向Excel中写入表格的表头int displayColumnsCount = 1;for (int i = 0; i <= dgv.ColumnCount - 1; i++){if (dgv.Columns[i].Visible == true){objExcel.Cells[1,displayColumnsCount] =dgv.Columns[i].HeaderText.Trim();displayColumnsCount++;}}//设置进度条//tempProgressBar.Refresh();//tempProgressBar.Visible = true;//tempProgressBar.Minimum=1;//tempProgressBar.Maximum=dgv.RowCount;//tempProgressBar.Step=1;//向Excel中逐行逐列写入表格中的数据for (int row = 0; row <= dgv.RowCount - 1; row++){//tempProgressBar.PerformStep();displayColumnsCount = 1;for (int col = 0; col < colscount; col++){if (dgv.Columns[col].Visible == true){try{objExcel.Cells[row + 2, displayColumnsCount] =dgv.Rows[row].Cells[col].Value.ToString().Trim();displayColumnsCount++;}catch (Exception){}}}}//隐藏进度条//tempProgressBar.Visible = false;//保存文件objWorkbook.SaveAs(fileNameString, Missing.Value, Missing.Value, Missing.Value, Missing.Value,Missing.Value,Excel.XlSaveAsAccessMode.xlShared, Missing.Value, Missing.Value, Missing.Value,Missing.Value, Missing.Value);}catch (Exception error){MessageBox.Show(error.Message, "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);return;}finally{//关闭Excel应用if (objWorkbook != null)objWorkbook.Close(Missing.Value, Missing.Value, Missing.Value);if (objExcel.Workbooks != null)objExcel.Workbooks.Close();if (objExcel != null) objExcel.Quit();objsheet = null;objWorkbook = null;objExcel = null;}MessageBox.Show(fileNameString + "\n\n导出完毕! ", "提示", MessageBoxButtons.OK,rmation);}#endregion/haokaibo/DataGridViewToExcel.ra r/haokaibo/DataGridViewToExcel.ra r。