Winform导入导出EXCEL
Winform开发框架之通用数据导入导出操作的事务性操作完善
Winform开发框架之通⽤数据导⼊导出操作的事务性操作完善1、通⽤数据导⼊导出操作模块回顾在我的Winfrom开发框架⾥⾯,有⼀个通⽤的导⼊模块,它在默默处理这把规范的Excel数据导⼊到不同的对象表⾥⾯,⼀直⽤它来快速完成数据导⼊的⼯作。
很早在随笔《》⾥⾯就很全⾯的介绍过它的相关功能了,在代码⽣成⼯具Database2Sharp⾥⾯,⽣成的Winfrom界⾯代码也已经把它的调⽤代码放进去了,因此使⽤起来真是很好,很开⼼。
在不断的项⽬实践中,发现使⽤基于Sqlite的客户端作为单机版的操作也越来越多,因此⼤批量的数据导⼊,也是经常碰到的事情,我们知道,SqlServer批量插⼊数据会很快,即使你没有使⽤事务,⼀条条的插⼊,⼤批量也会⽐较快,这个可能得益于SqlServer本⾝的事务优化效果。
但是作为单机版的数据库,Sqlite每次操作都是单独⼀个事务的,插⼊⼀条数据效率可能不明显,如果操作⼀千条,⼀万条,数据的缓慢就很明显,甚⾄不可忍耐了。
我曾经在《》⾥⾯提到了批量插⼊通⽤字典模块的字典数据,使⽤事务前后批量插⼊数据,那个速度可是差别很⼤。
基于以上的因素考虑,决定对通⽤的数据导⼊模块进⾏事务性的优化,以便适应我频繁使⽤Sqlite数据库⼤批量导⼊数据的情况,提⾼客户的良好体验。
本篇主要基于事务性操作的完善,实现基于Sqlite数据的批量快速导⼊操作。
2、事务性代理事件的定义由于是通⽤的模块,所以我们不知道具体的数据库事务对象,但是我们能够通过定义⼀些事件,给调⽤者进⾏事务对象的传递,这样才能在基类中使⽤事务对象,⾸先我们定义两个委托事件,⼀个是SaveDataHandler,⽤来进⾏单条数据的处理委托,⼀个是CreateTransactionHandler,让调⽤者创建并传递事务对象的委托,具体代码如下所⽰。
public partial class FrmImportExcelData : BaseForm{...............................private DbTransaction transaction = null;///<summary>///使⽤事务对数据进⾏保存的委托,加快速度///</summary>///<param name="dr">数据⾏</param>///<param name="trans">事务对象</param>///<returns></returns>public delegate bool SaveDataHandler(DataRow dr, DbTransaction trans);///<summary>///创建事务对象的委托,在导⼊操作初始化的时候赋值///</summary>///<returns></returns>public delegate DbTransaction CreateTransactionHandler();定义好委托后,我们需要创建对应委托的事件对象,作为通⽤模块的事件,如下所⽰。
Winform中Excel数据导入与导出
return;
}
string filepath=txtpath.Text;
SqlConnection conn =new SqlConnection(strcon);//链接数据库
winform实现Excel表格导入Sql数据库示例
winform实现Excel表格导入Sql数据库示例,首先要保证的是将要导入数据库的excel表格中的数据和数据库字段相符,excel中不能存在数据表中不存在的字段。获取excel文档完整路径,并将其中的数据生成dataset对象:
private DataSet xsldata(string filepath)
DateTime stdt = Convert.ToDateTime(ds.Tables[0].Rows[i][4].ToString());
string cardstate= ds.Tables[0].Rows[i][5].ToString();
string strCom = "SELECT * FROM [Sheet1$]";
Conn.Open();
System.Data.OleDb.OleDbDataAdapter myCommand = new System.Data.OleDb.OleDbDataAdapter(strCom, Conn);
conn.Open();
try
{
DataSet ds = new DataSet();
//取得数据集
//调用上面的函数
ds = xsldata(filepath);
{
if(txtpath.Text=="")
{
把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_将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());。
winform中DataGridView导出Excel(使用NPOI,速度最快的一种方法)
winform中DataGridView导出Excel(使⽤NPOI,速度最快的⼀种⽅法)1,在⽹上搜索到的⼀般是这种通⽤的⽅法,这个⽅法速度太慢了,代码如下private void ExportExcel(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);}2,最近研究了半天,使⽤NOPI的⽅法真是的太快了,秒存的感觉【2.1】使⽤:private void btn_export_Click(object sender, EventArgs e){try{ExcelHelper.ExportToExcel(this.dgv_data);new FrmConfirmSingle("⽇志导出", "⽇志记录导出成功") { TopMost = true }.ShowDialog();}catch (Exception exception){new FrmConfirmSingle("⽇志导出", "⽇志记录导出失败:"+exception.Message) { TopMost = true }.ShowDialog();}} 【2.2】主要代码如下:/// <summary>/// 由DataGridView导出Excel/// </summary>/// <param name="grid"></param>/// <param name="sheetName"></param>/// <param name="filePath"></param>/// <returns></returns>public static string ExportToExcel(DataGridView grid, string sheetName = "result", string filePath = null){if (grid.Rows.Count <= 0) return null;if (string.IsNullOrEmpty(filePath)){filePath = GetSaveFilePath();}IWorkbook workbook = CreateWorkbook(isCompatible);ICellStyle cellStyle = GetCellStyle(workbook);ISheet sheet = workbook.CreateSheet(sheetName);IRow headerRow = sheet.CreateRow(0);for (int i = 0; i < grid.Columns.Count; i++){ICell cell = headerRow.CreateCell(i);cell.SetCellValue(grid.Columns[i].Name);cell.CellStyle = cellStyle;}int rowIndex = 1;foreach (DataGridViewRow row in grid.Rows){IRow dataRow = sheet.CreateRow(rowIndex);for (int n = 0; n < grid.Columns.Count; n++){dataRow.CreateCell(n).SetCellValue((row.Cells[n].Value ?? "").ToString());}rowIndex++;}AutoColumnWidth(sheet, stCellNum - 1);FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);workbook.Write(fs);fs.Dispose();sheet = null;headerRow = null;workbook = null;MessageBox.Show("⽂件: " + filePath + ".xls 保存成功", "信息提⽰", MessageBoxButtons.OK, rmation); return filePath;} 【2.3】下⾯是我整理的通⽤EXCEL的帮助类,⾮常的实⽤using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.IO;using System.Data;using System.Windows.Forms;using erModel;using erModel;using erModel;using System.Collections;using pilerServices;/** 须在项⽬中添加引⽤ NPOI.dll NPOI.OOXML.dll NPOI.OPenXml4Net.dll*/namespace AutomaticStoreMotionDal{public static class ExcelHelper{/// <summary>/// 获取要保存的⽂件名称(含完整路径)/// </summary>/// <returns></returns>public static string GetSaveFilePath(){SaveFileDialog saveFileDig = new SaveFileDialog();saveFileDig.Filter = "Excel Office97-2003(*.xls)|*.xls|Excel Office2007及以上(*.xlsx)|*.xlsx";saveFileDig.FileName = DateTime.Now.ToString("yyyyMMddHHmmss");saveFileDig.FilterIndex = 0;saveFileDig.OverwritePrompt = true;string dir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);//获取当前系统桌⾯路径saveFileDig.InitialDirectory = dir;string filePath = null;if (saveFileDig.ShowDialog() == DialogResult.OK){filePath = saveFileDig.FileName;}return filePath;}/// <summary>/// 打开⽂件对话框,并返回⽂件的路径/// </summary>/// <returns></returns>public static string GetOpenFilePath(){//创建对话框的对象ofd.Multiselect = true;//设置对话框的初始⽬录ofd.InitialDirectory = @"C:\Users\Administrator\Desktop";//设置对话框打开⽂件的类型ofd.Filter = "Excel⽂件(.xls)|*.xls|Excel⽂件(.xlsx)|*.xlsx";//展⽰对话框ofd.ShowDialog();//获得在打开对话框中选中的⽂件的路径string filePath = ofd.FileName;//全路径return filePath;}/// <summary>/// 判断Excel⽂件是否为兼容模式(.xls)/// </summary>/// <param name="filePath"></param>/// <returns></returns>public static bool GetIsCompatible(string filePath){return filePath.EndsWith(".xls", StringComparison.OrdinalIgnoreCase);}/// <summary>/// 创建⼯作薄/// </summary>/// <param name="isCompatible">true就是.xls</param>/// <returns></returns>public static IWorkbook CreateWorkbook(bool isCompatible){if (isCompatible){return new HSSFWorkbook();}else{return new XSSFWorkbook();}}/// <summary>/// 创建⼯作薄(依据⽂件流)/// </summary>/// <param name="isCompatible"></param>/// <param name="stream"></param>/// <returns></returns>public static IWorkbook CreateWorkbook(bool isCompatible, Stream stream) {if (isCompatible){return new HSSFWorkbook(stream);}else{return new XSSFWorkbook(stream);}}#region 传⼊⼀个⽂件路径,返回⼀个IWorkbook对象/// <summary>/// 传⼊⼀个⽂件路径,返回⼀个IWorkbook对象/// </summary>/// <param name="filepath"></param>/// <returns></returns>public static IWorkbook CreateWorkbook(string filepath){IWorkbook workbook = null;bool isCompatible = ExcelHelper.GetIsCompatible(filepath);using (FileStream fs = File.Open(filepath, FileMode.Open,FileAccess.Read, FileShare.ReadWrite)){//把xls⽂件读⼊workbook变量⾥,之后就可以关闭了workbook = ExcelHelper.CreateWorkbook(isCompatible, fs);fs.Close();}return workbook;}#endregion#region 打开⼀个excel⽂件,设置单元格的值,再保存⽂件/// <summary>/// 打开⼀个excel⽂件,设置单元格的值,再保存⽂件/// </summary>/// <param name="ExcelPath"></param>/// <param name="sheetname"></param>/// <param name="column"></param>public static bool SetCellValue(String ExcelPath, String sheetname, int column, int row, String value) {bool returnb = false;try{IWorkbook wk = null;bool isCompatible = ExcelHelper.GetIsCompatible(ExcelPath);using (FileStream fs = File.Open(ExcelPath, FileMode.Open,FileAccess.Read, FileShare.ReadWrite)){//把xls⽂件读⼊workbook变量⾥,之后就可以关闭了wk = ExcelHelper.CreateWorkbook(isCompatible, fs);fs.Close();}//把xls⽂件读⼊workbook变量⾥,之后就可以关闭了//ISheet sheet = wk.GetSheet(sheetname);ISheet sheet = wk.GetSheetAt(0);ICell cell = sheet.GetRow(row).GetCell(column);cell.SetCellValue(value);using (FileStream fileStream = File.Open(ExcelPath,FileMode.OpenOrCreate, FileAccess.ReadWrite)){wk.Write(fileStream);fileStream.Close();}returnb = true;}catch (Exception){returnb = false;throw;}return returnb;}#endregion#region 打开⼀个⽂件,读取excel⽂件某个单元格的值(多少⾏,多少列)/// <summary>/// 打开⼀个⽂件,读取excel⽂件某个单元格的值(多少⾏,多少列)/// </summary>/// <param name="ExcelPath"></param>/// <param name="sheetname"></param>/// <param name="column"></param>/// <param name="row"></param>/// <returns></returns>public static String GetCellValue(string ExcelPath, String sheetname, int column, int row){String returnStr = null;try{IWorkbook wk = null;bool isCompatible = ExcelHelper.GetIsCompatible(ExcelPath);using (FileStream fs = File.Open(ExcelPath, FileMode.Open,FileAccess.Read, FileShare.ReadWrite)){//把xls⽂件读⼊workbook变量⾥,之后就可以关闭了wk = ExcelHelper.CreateWorkbook(isCompatible, fs);fs.Close();}//把xls⽂件读⼊workbook变量⾥,之后就可以关闭了//ISheet sheet = wk.GetSheet(sheetname);ISheet sheet = wk.GetSheetAt(0);ICell cell = sheet.GetRow(row).GetCell(column);returnStr = cell.ToString();}catch (Exception){returnStr = "Exception";throw;}return returnStr;}#endregion#region 打开⼀个⽂件,删除多少⾏以后的数据(是删除,不是清空数据)/// <summary>/// 打开⼀个⽂件,删除多少⾏以后的数据(是删除,不是清空数据)/// </summary>/// <param name="fileMatchPath"></param>/// <param name="rowIndex">从多少⾏后开始删除</param>public static void DelRowsData(string fileMatchPath, int startRowIndex){IWorkbook wk = null;bool isCompatible = ExcelHelper.GetIsCompatible(fileMatchPath);using (FileStream fs = File.Open(fileMatchPath, FileMode.Open,FileAccess.Read, FileShare.ReadWrite)){//把xls⽂件读⼊workbook变量⾥,之后就可以关闭了ISheet sheet = wk.GetSheetAt(0);for (int i = startRowIndex; i <= stRowNum; i++){if (sheet.GetRow(i) == null){i++;continue;}sheet.RemoveRow(sheet.GetRow(i));}//转为字节数组MemoryStream stream = new MemoryStream();wk.Write(stream);var buf = stream.ToArray();//保存为Excel⽂件这种⽅式能保存.xls和.xlsx⽂件using (FileStream fs = new FileStream(fileMatchPath, FileMode.Create, FileAccess.Write)){fs.Write(buf, 0, buf.Length);fs.Flush();}}#endregion/// <summary>/// 创建表格头单元格/// </summary>/// <param name="sheet"></param>/// <returns></returns>private static ICellStyle GetCellStyle(IWorkbook workbook){ICellStyle style = workbook.CreateCellStyle();style.FillPattern = FillPattern.SolidForeground;style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;return style;}/// <summary>/// 遍历打印⼆维数组/// </summary>/// <param name="array"></param>public static void PrintTwoArrayTest(object[,] array){Console.WriteLine("============测试打印⼆维数组==============");int row = array.GetLength(0);int column = array.GetLength(1);for (int r = 0; r < row; r++){for (int c = 0; c < column; c++){if (array[r, c] != null){string value = array[r, c].ToString();Console.Write($"{value} |");}}Console.WriteLine();}}/// <summary>/// 传⼊2个⼆维数组,进⾏条件匹配替换,返回替换后的⼀个⼆维数组/// </summary>/// <param name="refArray">参考的数组</param>/// <param name="matchArray">带替换的数组</param>/// <param name="refColumn01">参考列1</param>/// <param name="refColumn02">参考列2</param>/// <param name="refColTarget01">被复制的值的列1</param>/// <param name="matchColumn01">带替换的参考列1</param>/// <param name="matchColumn02">带替换的参考列2</param>/// <param name="matchColTarget01">带粘贴的值的列1</param>/// <returns></returns>public static string[,] GetMatchArray(string[,] refArray, string[,] matchArray, int refColumn01, int refColumn02, int refColTarget01, int matchColumn01, int matchColumn02, int matchColTarget01) {Console.WriteLine("============遍历2个⼆维数,匹配替换==============");int row = refArray.GetLength(0);int column = matchArray.GetLength(1);int row02 = matchArray.GetLength(0);int iMatch = 0;for (int r = 0; r < row; r++){string value01 = refArray[r, refColumn01];//第1列的数据string value02 = refArray[r, refColumn02];//第2列的数据if (value01 != null && value02 != null){if (value01.Length > 0 | value02.Length > 0){for (int r02 = 0; r02 < row02; r02++){{matchArray[r02, matchColTarget01] = refArray[r, refColTarget01];iMatch++;Console.WriteLine($"匹配了{iMatch}次");}}}}}return matchArray;}/// <summary>/// 传⼊2个数组,根据相同条件匹配,吧ref的⽬标写⼊match中/// </summary>/// <param name="refArray">参考的数组</param>/// <param name="matchArray">带替换的数组</param>/// <param name="refColumn01"></param>/// <param name="refColTarget01"></param>/// <param name="matchColumn01"></param>/// <param name="matchColTarget01"></param>/// <returns></returns>public static string[,] GetMatchArray(string[,] refArray, string[,] matchArray, int refColumn01, int refColTarget01, int matchColumn01, int matchColTarget01) {Console.WriteLine("============遍历2个⼆维数,匹配替换==============");int row = refArray.GetLength(0);int column = matchArray.GetLength(1);int row02 = matchArray.GetLength(0);int iMatch = 0;for (int r = 0; r < row; r++){string value01 = string.Empty;value01 = refArray[r, refColumn01];//遍历第⼀个数组第1列的数据//value01 = value01.Trim();if (value01 != null){if (value01.Length > 0){for (int r02 = 0; r02 < row02; r02++){string match01 = string.Empty;match01 = matchArray[r02, matchColumn01];//遍历第⼀个数组第1列的数据//match01 = match01.Trim();if (value01 == match01){matchArray[r02, matchColTarget01] = refArray[r, refColTarget01];iMatch++;Console.WriteLine($"匹配了{iMatch}次");}}}}}return matchArray;}/// <summary>/// 遍历⼀个数组,如果第⼆列的数值⼤于等于第⼀列的数值,替换字符串/// </summary>/// <param name="matchArray"></param>/// <param name="refColumn01"></param>/// <param name="refColumn02"></param>/// <param name="sValue"></param>/// <returns></returns>public static string[,] GetMatchArray(string[,] matchArray, int refColumn01, int refColumn02, string sValue){Console.WriteLine("============遍历2个⼆维数,匹配替换==============");int row = matchArray.GetLength(0);int column = matchArray.GetLength(1);int iMatch = 0;for (int r = 0; r < row; r++){string value01 = matchArray[r, refColumn01];//第1列的数据string value02 = matchArray[r, refColumn02];//第2列的数据try{int i01 = Convert.ToInt32(value01);int i02 = Convert.ToInt32(value02);if (i01 >= i02){matchArray[r, refColumn02] = sValue + $"(数量:{value02})";}}catch{}}return matchArray;}#region 打开excel⽂件,获取某⼀⾏的数据/// <param name="filepath">⽂件全路径</param>/// <param name="iRow">哪⼀⾏的数据</param>/// <param name="sheet_Number">哪⼀个sheet表</param>/// <returns></returns>public static ArrayList GetRowData(string filepath, int sheet_Number, int iRow){ArrayList arrayList = new ArrayList();bool isCompatible = ExcelHelper.GetIsCompatible(filepath);using (FileStream fsRead = File.OpenRead(filepath)){IWorkbook workbook = ExcelHelper.CreateWorkbook(isCompatible, fsRead);ISheet sheet = workbook.GetSheetAt(sheet_Number - 1);IRow currentRow = sheet.GetRow(iRow - 1);for (int c = 0; c < stCellNum; c++){//获取每个单元格(r⾏c列的数据)ICell cell = currentRow.GetCell(c);//获取单元格的内容string value = string.Empty;if (cell != null){value = cell.ToString(); //如果单元格为空,这⾥会报错的arrayList.Add(value);}}return arrayList;}}#endregion/// <summary>/// 打开excel⽂件,根据某⼀⾏的数据,根据字符串内容,返回这个字符串所在的列的索引/// </summary>/// <param name="filepath"></param>/// <param name="iRow"></param>/// <param name="sheet_Number">从1开始的</param>/// <param name="s1">注意字符串的顺序</param>/// <param name="s2"></param>/// <param name="s3"></param>/// <returns></returnsspublic static ArrayList GetDataIndexs(string filepath, int sheet_Number, int iRow, string s1, string s2, string s3) {ArrayList arrayList = new ArrayList();bool isCompatible = ExcelHelper.GetIsCompatible(filepath);using (FileStream fsRead = File.OpenRead(filepath)){IWorkbook workbook = ExcelHelper.CreateWorkbook(isCompatible, fsRead);ISheet sheet = workbook.GetSheetAt(sheet_Number - 1);IRow currentRow = sheet.GetRow(iRow - 1);for (int c = 0; c < stCellNum; c++){//获取每个单元格(r⾏c列的数据)ICell cell = currentRow.GetCell(c);//获取单元格的内容string value = string.Empty;if (cell != null){value = cell.ToString(); //如果单元格为空,这⾥会报错的if (value == s1 | value == s2 || value == s3){arrayList.Add(c);}}}Console.WriteLine("==========测试打印索引值============");foreach (var a in arrayList){Console.WriteLine($"{a} |");}return arrayList;}}/// <summary>/// 打开excel⽂件,根据某⼀⾏的字符串,然后这个字符串所在列的索引/// </summary>/// <param name="filepath"></param>/// <param name="sheet_Number"></param>/// <param name="iRow"></param>/// <param name="sValue"></param>/// <returns></returns>public static int GetDataIndex(string filepath, int sheet_Number, int iRow, string sValue){int i = 0;bool isCompatible = ExcelHelper.GetIsCompatible(filepath);using (FileStream fsRead = File.OpenRead(filepath)){IWorkbook workbook = ExcelHelper.CreateWorkbook(isCompatible, fsRead);ISheet sheet = workbook.GetSheetAt(sheet_Number - 1);IRow currentRow = sheet.GetRow(iRow - 1);for (int c = 0; c < stCellNum; c++){//获取每个单元格(r⾏c列的数据)ICell cell = currentRow.GetCell(c);value = cell.ToString(); //如果单元格为空,这⾥会报错的if (value == sValue){i = c;}}}}return i;}/// <summary>/// 打开⼀个⽂件,把第⼏⾏的数据取出来,返回⼀个字典单元格的值:列的索引/// </summary>/// <param name="filepath"></param>/// <param name="sheet_Number">第⼏张⼯作表(从1开始)</param>/// <param name="iRow">第⼏⾏(从1开始)</param>/// <returns></returns>public static Dictionary<string, int> GetDataDictionary(string filepath, int sheet_Number, int iRow){Dictionary<string, int> DataDict = new Dictionary<string, int>();bool isCompatible = ExcelHelper.GetIsCompatible(filepath);using (FileStream fsRead = File.OpenRead(filepath)){IWorkbook workbook = ExcelHelper.CreateWorkbook(isCompatible, fsRead);ISheet sheet = workbook.GetSheetAt(sheet_Number - 1);IRow currentRow = sheet.GetRow(iRow - 1);for (int c = 0; c < stCellNum; c++){//获取每个单元格(r⾏c列的数据)ICell cell = currentRow.GetCell(c);//获取单元格的内容string value = string.Empty;if (cell != null){value = cell.ToString(); //如果单元格为空,这⾥会报错的if (!DataDict.ContainsKey(value)){if (value == "*预计交货⽇期" | value == "预计交货⽇期"){value = "*预计交货⽇期";}DataDict.Add(value, c);}else{if (filepath.Contains("销售订单")) //销售订单模板的第⼆个备注填写收货地址{if (value == "备注") //如果有两个备注{//DataDict.Add("采购员", c);DataDict.Add("收货地址", c);}}}}}//Console.WriteLine("================开始遍历字典===============");//foreach (KeyValuePair<string, int> kv in DataDict)//通过KeyValuePair遍历元素//{// Console.WriteLine($"Key:{kv.Key},Value:{kv.Value}");//}return DataDict;}}/// <summary>/// 打开⼀个⽂件,根据第⼏张表第⼏⾏的中的两个字符,返回值:⼀个字典/// </summary>/// <param name="filepath"></param>/// <param name="sheet_Number"></param>/// <param name="strColumnKey"></param>/// <param name="strColumnValue"></param>/// <returns></returns>public static Dictionary<string, string> GetDataDictionary(string filepath, int sheet_Number, int iRow, string strColumnKey, string strColumnValue) {Dictionary<string, int> dic = GetDataDictionary(filepath, 1, iRow);int iColumnKey = dic[strColumnKey];int iColumnValue = dic[strColumnValue];Dictionary<string, string> DataDict = new Dictionary<string, string>();bool isCompatible = ExcelHelper.GetIsCompatible(filepath);using (FileStream fsRead = File.OpenRead(filepath)){IWorkbook workbook = ExcelHelper.CreateWorkbook(isCompatible, fsRead);ISheet sheet = workbook.GetSheetAt(sheet_Number - 1);for (int i = 0; i <= stRowNum; i++)ICell cellKey = rowdata.GetCell(iColumnKey);//如果rowdata是null,这⾥报错ICell cellValue = rowdata.GetCell(iColumnValue);if (cellKey != null && cellValue != null){if (!DataDict.ContainsKey(cellKey.ToString())){string strCellKey = cellKey.ToString();string strCellValue = cellValue.ToString();DataDict.Add(strCellKey, strCellValue);}}}}return DataDict;}}/// <summary>/// ⾃适应列宽/// </summary>/// <param name="sheet"></param>/// <param name="cols"></param>public static void AutoColumnWidth(ISheet sheet, int cols){for (int col = 0; col <= cols; col++){sheet.AutoSizeColumn(col);//⾃适应宽度,但是其实还是⽐实际⽂本要宽int columnWidth = sheet.GetColumnWidth(col) / 256;//获取当前列宽度for (int rowIndex = 1; rowIndex <= stRowNum; rowIndex++){IRow row = sheet.GetRow(rowIndex);ICell cell = row.GetCell(col);if (cell != null){int contextLength = Encoding.UTF8.GetBytes(cell.ToString()).Length;//获取当前单元格的内容宽度 columnWidth = columnWidth < contextLength ? contextLength : columnWidth;}}sheet.SetColumnWidth(col, columnWidth * 200);//经过测试200⽐较合适。
把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对EXCEL的操作(一)
WinForm对EXCEL的操作(⼀)由于⼯作原因,最近对EXCEL⽂件的操作和数据导⼊导出进⾏了学习。
并把其中的⼀些常⽤⽅法总结出来,不敢私藏现在分享给⼤家。
不⾜之处,还请指正。
(⼀)获取EXCEL⽂件SHEET的名称⽅法1:View Code1public static string[] ExcelTableNames(string FileName)2 {3string strXls = FileName.Substring(stIndexOf(".")).ToLower();4string sConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FileName + ";Extended Properties=Excel 8.0";5string[] ss = "";6string temp = "'$";7using (OleDbConnection oleConn = new OleDbConnection())8 {9 oleConn.ConnectionString = sConn;10try11 {12 oleConn.Open();13 DataTable table = oleConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);14if (table == null || table.Rows.Count == 0) return ss;15 ss = new string[table.Rows.Count];16for (int i = 0; i < table.Rows.Count; ++i)17 {18 ss[i] = table.Rows[i]["Table_Name"].ToString();19// 由于如何sheet名称为中⽂字符,在获取如何shee和名称时会有$ '字符,所以使⽤了字符过滤。
C# WinForm导入导出Excel
Excel.Workbook wb = wbs.Open(filePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Microsoft.Office.Interop.Excel.ApplicationClass excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
excel.Application.Workbooks.Add(true); ;
saveFileDialog.Title = "导出文件保存路径";
saveFileDialog.ShowDialog();
string strName = saveFileDialog.FileName;
System.Runtime.InteropServices.Marshal.ReleaseComObject(book);
System.Runtime.InteropServices.Marshal.ReleaseComObject(books);
toolStripProgressBar1.Value = 0;
System.Diagnostics.Process.Start(strName);
}
}
else
{
excel.Cells[i + 2, j ] = gridView[j, i].Value.ToString();
= "test";
int m = 0, n = 0;
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)
C#winform导出导入ExcelDoc完整实例教程[网上看到的]
C#winform导出导⼊ExcelDoc完整实例教程[⽹上看到的]还真没做过winform的导出导⼊,今天上⽹百度了⼀下。
结果---所以还是我⾃⼰写个吧。
之前做过web的,半搬半做就OK。
1添加引⽤:Aspose.Cells.dll(我们就叫⼯具包吧,可以从⽹上下载。
关于它的操作我在“Aspose.Cells操作说明中⽂版下载 Aspose C# 导出Excel 实例”⼀⽂中的说。
这⾥你暂时也可不理会它。
)Aspose.Cells.dll 和中⽂说明下载地址:即使没有安装office也能⽤噢,这是⼀个好强的⼤⼯具。
2编写Excel操作类using System;using System.Collections.Generic;using System.Text;using Aspose.Cells;using System.Data;public class AsposeExcel{private string outFileName = "";private string fullFilename = "";private Workbook book = null;private Worksheet sheet = null;public AsposeExcel(string outfilename, string tempfilename)//导出构造数{outFileName = outfilename;book = new Workbook();// book.Open(tempfilename);这⾥我们暂时不⽤模板sheet = book.Worksheets[0];}public AsposeExcel(string fullfilename)//导⼊构造数{fullFilename = fullfilename;// book = new Workbook();//book.Open(tempfilename);//sheet = book.Worksheets[0];}private void AddTitle(string title, int columnCount){sheet.Cells.Merge(0, 0, 1, columnCount);sheet.Cells.Merge(1, 0, 1, columnCount);Cell cell1 = sheet.Cells[0, 0];cell1.PutValue(title);cell1.Style.HorizontalAlignment = TextAlignmentType.Center; = "⿊体";cell1.Style.Font.Size = 14;cell1.Style.Font.IsBold = true;Cell cell2 = sheet.Cells[1, 0];cell1.PutValue("查询时间:" + DateTime.Now.ToLocalTime());cell2.SetStyle(cell1.Style);}private void AddHeader(DataTable dt){Cell cell = null;for (int col = 0; col < dt.Columns.Count; col++){cell = sheet.Cells[0, col];cell.PutValue(dt.Columns[col].ColumnName);cell.Style.Font.IsBold = true;}}private void AddBody(DataTable dt){for (int r = 0; r < dt.Rows.Count; r++){for (int c = 0; c < dt.Columns.Count; c++){sheet.Cells[r + 1, c].PutValue(dt.Rows[r][c].ToString());}}}//导出------------下⼀篇会⽤到这个⽅法public Boolean DatatableToExcel(DataTable dt){Boolean yn = false;try{// = sheetName;//AddTitle(title, dt.Columns.Count);//AddHeader(dt);AddBody(dt);sheet.AutoFitColumns();//sheet.AutoFitRows();book.Save(outFileName);yn = true;return yn;}catch (Exception e){return yn;// throw e;}}public DataTable ExcelToDatatalbe()//导⼊{Workbook book = new Workbook();book.Open(fullFilename);Worksheet sheet = book.Worksheets[0];Cells cells = sheet.Cells;//获取excel中的数据保存到⼀个datatable中DataTable dt_Import = cells.ExportDataTableAsString(0, 0, cells.MaxDataRow + 1, cells.MaxDataColumn + 1, false); // dt_Import.return dt_Import;}}3导出按钮事件中编写导出数据⽅法:private void bt_excel_out_Click(object sender, EventArgs e){SaveFileDialog saveFileDialog1 = new SaveFileDialog();//如果你直接从对话框中拉出来,就不⽤new了噢。
winform应用使用DataGridView数据导出到Excel
Missing.Value, Excel.XlSaveAsAccessMode.xlShared, Missing.Value, Missing.Value, Missing.Valu
用
if (objWorkbook != null) objWorkbook.Close(Missing.Value, Missing.Value, Missing.Value);
t ry
{
f ile.Delet e();
}
catch (Exception error)
{
MessageBox.Show(error.Message, "删除失败 ", M
头
int displayColumnsCount = 1;
for (int i = 0; i <= dgv.ColumnCount - 1; i++)
径 dlg.InitialDirectory = Directory.GetCurrentDirectory(); //打开保存对话框 if (dlg.ShowDialog() == DialogResult.Cancel) return; //返回文件路径 string fileNameString = dlg.FileName; //验证strF
示 ", MessageBoxButtons.OK, rmation);
return; }
//行数不可以大于65536 if (rowscount > 65536) {
MessageBo x.Sho w("数据记录数太多(最多不能超过65536条),
它 FileInfo file = new FileInfo(fileNameString); if (file.Exists) {
C#Winform实现导入和导出Excel文件
C#Winform实现导⼊和导出Excel⽂件本⽂实例为⼤家分享了Winform实现导⼊导出Excel⽂件的具体代码,供⼤家参考,具体内容如下/// <summary>/// 导出Excel⽂件/// </summary>/// /// <param name="dataSet"></param>/// <param name="dataTable">数据集</param>/// <param name="isShowExcle">导出后是否打开⽂件</param>/// <returns></returns>public static bool DataTableToExcel(string filePath, System.Data.DataTable dataTable, bool isShowExcle){//System.Data.DataTable dataTable = dataSet.Tables[0];int rowNumber = dataTable.Rows.Count;int columnNumber = dataTable.Columns.Count;int colIndex = 0;if (rowNumber == 0){return false;}Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];excel.Visible = isShowExcle;Microsoft.Office.Interop.Excel.Range range;foreach (DataColumn col in dataTable.Columns){colIndex++;excel.Cells[1, colIndex] = col.ColumnName;}object[,] objData = new object[rowNumber, columnNumber];for (int r = 0; r < rowNumber; r++){for (int c = 0; c < columnNumber; c++){objData[r, c] =dataTable.Rows[r][c];}}range = worksheet.get_Range(excel.Cells[2, 1], excel.Cells[rowNumber + 1, columnNumber]);range.Value2 = objData;range.NumberFormatLocal = "@";worksheet.SaveAs(filePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); //excel.Quit();return true;}读取Excel⽂件数据到DataTable/// <summary>/// 读取Excel⽂件数据到DataTable/// </summary>/// <param name="filePath">Excel⽂件路径</param>private void Import_Excel(string filePath){string sqlconn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'";string sql = @"select * from [Sheet1$]";try{using (OleDbConnection conn = new OleDbConnection(sqlconn)){using (OleDbDataAdapter adapter = new OleDbDataAdapter(sql, conn)){System.Data.DataTable dt = new System.Data.DataTable();adapter.Fill(dt);this.LoadDataGridView(dt);}}}catch (Exception ex){MessageBox.Show("打开⽂件出错,错误信息:" + ex.Message.ToString(), "提⽰");}}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
C#数据导入导出Excel文件及winForm导出Execl总结
C#数据导⼊导出Excel⽂件及winForm导出Execl总结在中导出Execl有两种⽅法,⼀种是将导出的⽂件存放在服务器某个⽂件夹下⾯,然后将⽂件地址输出在浏览器上;⼀种是将⽂件直接将⽂件输出流写给浏览器。
在Response输出时,\t分隔的数据,导出execl时,等价于分列,\n等价于换⾏。
此法将html中所有的内容,如按钮,表格,图⽚等全部输出到Execl中。
复制代码代码如下:Response.Clear();Response.Buffer= true;Response.AppendHeader("Content-Disposition","attachment;filename="+DateTime.Now.ToString("yyyyMMdd")+".xls");Response.ContentEncoding=System.Text.Encoding.UTF8;Response.ContentType = "application/vnd.ms-excel";this.EnableViewState = false;这⾥我们利⽤了ContentType属性,它默认的属性为text/html,这时将输出为超⽂本,即我们常见的⽹页格式到客户端,如果改为ms-excel将将输出excel格式,也就是说以电⼦表格的格式输出到客户端,这时浏览器将提⽰你下载保存。
ContentType的属性还包括:image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword 。
同理,我们也可以输出(导出)图⽚、word⽂档等。
下⾯的⽅法,也均⽤了这个属性。
上述⽅法虽然实现了导出的功能,但同时把按钮、分页框等html中的所有输出信息导了进去。
⽽我们⼀般要导出的是数据,DataGrid控件上的数据。
Winform导出Excel的列格式设置
Winform导出Excel的列格式设置最近,在做winform项目中遇到了将数据添加到excle中,其中也涉及到数据的格式问题,在网上搜索了一番,找到一编解决的文章,特保存下来,以备不时之需。
Winform导出Excel的列格式设置在项目中一般都需要将报表数据导出到EXCEL中,但经常出现导出长串数据(如身份证)到EXCEL中后显示为科学计数法的格式,或者报表中显示为001的数据导出到Excel后成了1的格式。
下面简单介绍一下以上问题的解决方法:protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e){if (e.Row.RowType == DataControlRowType.DataRow)e.Row.Cells[1].Attributes.Add("style", "vnd.ms-excel.numberformat:@");}1、首先,了解一下excel从web页面上导出的原理。
当我们把这些数据发送到客户端时,我们想让客户端程序(浏览器)以excel的格式读取它,所以把mime类型设为:application/vnd.ms-excel,当excel读取文件时会以每个cell的格式呈现数据,如果cell没有规定的格式,则excel会以默认的格式去呈现该cell的数据。
这样就给我们提供了自定义数据格式的空间,当然我们必须使用excel支持的格式。
下面就列出常用的一些格式:1)文本:vnd.ms-excel.numberformat:@2)日期:vnd.ms-excel.numberformat:yyyy/mm/dd3)数字:vnd.ms-excel.numberformat:#,##0.004)货币:vnd.ms-excel.numberformat:¥#,##0.005)百分比:vnd.ms-excel.numberformat: #0.00%方法2:m_objSheet.get_Range("A2",m_objExcel.Cells[nCountRow+1,1]).NumberFormat = "@";m_objSheet.get_Range("A2",m_objExcel.Cells[nCountRow+1,1]).NumberFormat = "00000";这种方法看似可以,但是点击单元格,还是int型。
C#WinForm开发系列-Excel
C#WinForm开发系列-Excel01.[翻译]Senthil S著[简介]当前,⽹上已经有了不少的导⼊数据到Excel⽂件的⽅法,不过⼤部分都⽐较复杂,它们⼤多采⽤Datagrid 或DataTable。
本⽂将介绍⼀种最简单的⽅法:仅使⽤Dataset 导出数据到Excel。
[背景]从代码使⽤的简单性⾓度,使⽤Dataset是⾮常⽅便的。
不过如果从代码优化的⾓度⽽⾔,就不再适合了:)02.快速保存ListView内存中⼤量数据到ExcelFast Save data from ListView to Excel WorkSheetremex1980 原创于 2007-5-19 19:59:27原作者: remex1980简介本⽂描述如何快速保存ListView内存中⼤量数据到Excel的WorkSheet。
关键之处是使⽤Range⼀次存储多⾏多列数据。
03.[翻译]Liu Junfeng著[简介]这个链接库是基于以下⼏篇⽂章编写出来的,⾮常感谢它们的作者:本⽂涉及了BIFF8/BIFF8X格式下的记录结构。
功能1. 读出在⼯作簿(workbook)中的所有Worksheet2. 读出所有WorkSheet中的单元3. 读取单元的内容(⽂本,数字,⽇期或错误)4. 读取单元的格式(字体,对齐,线条类型,背景等)5. 够读取⽂件中的图⽚,获取图象的⼤⼩,位置,数据和格式04.⽤途:帮辅导员填⼀个数据调查表,1个xls⽂件,有10个worksheet,每个中有10-40项数据要填写,每个班有37个⼈,学院有24个班。
如果逐个⼈填写需要很多时间。
可以将表格同时发给每个⼈,然后各⾃填好了⼀起发回来,放在同⼀个⽬录或其它位置,⽤此程序引⼊,然后做好设置,点批处理,稍后即可得到⼀个合并后的⽂件。
#表⽰⾃动识别⾏数和列数。
将操作Excel的代码封装在类中,可以通过调⽤类的⽅法实现各种操作,类可以同时打开⼏个Excel⽂件,在内部相互赋值。
NPOIwinform导出Excel
NPOIwinform导出Excel 引⽤命名空间using System.IO;using erModel;using NPOI.HSSF.Util;///<summary>///导出Excel的操作///</summary>///<param name="sender"></param>///<param name="e"></param>private void btnOpenExcel_Click(object sender, EventArgs e){//1创建⼯作簿 2创建⼯作表 3创建⾏ 4创建单元格 5单元格赋值//6合并单元格 7设置字体颜⾊ 8设置单元格底⾊ 9输出到⽂件//声明⼯作簿var wk = new XSSFWorkbook();//声明⼯作表var st = wk.CreateSheet();//创建⾏(默认从0⾏开始)var r = st.CreateRow(0);//创建单元格(默认从0⾏开始)var c = r.CreateCell(0);//赋值c.SetCellValue("你好");//合并单元格⾸⾏,尾⾏,⾸列.尾列var hb=new NPOI.SS.Util.CellRangeAddress(0,4,0,3);//A1:D5;//合并区域st.AddMergedRegion(hb);//设置字体颜⾊对象var MyFont = wk.CreateFont();//创建单元格样式var MyCellStyle = wk.CreateCellStyle();MyFont.FontHeightInPoints = 15;//15#字体MyFont.FontName = "微软雅⿊";//字体MyFont.Color = NPOI.HSSF.Util.HSSFColor.DarkBlue.Index;//字体颜⾊//单元格底⾊(填充样式)MyCellStyle.FillPattern = erModel.FillPattern.SolidForeground;MyCellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.LightGreen.Index;//嵌⼊字体MyCellStyle.SetFont(MyFont);//单元格样式赋值给单元格c.CellStyle = MyCellStyle;//写⼊⽂件流地址(完整路径) 创建写var fs = new FileStream(@"D:\stu\123.xlsx", FileMode.Create, FileAccess.Write);//写⼊wk.Write(fs);//关闭⽂件流fs.Close();MessageBox.Show("导出成功","提⽰信息");}。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
MessageBoxEx.Show("数据导入成功!");
}
else
{
MessageBoxEx.Show("请检查你的Excel中是否存在数据");
dt = DbHelperOleDb.Query_dt(sql);
//this.dataGridViewX2.DataSource = dt.DefaultView;
if (dt.Rows.Count > 0)
for (int i = 1; i <= count; i++)
{
names[i - 1] = ((Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[i]).Name;
string sql = "select * from [Excel 8.0;HDR=Yes;IMEX=1;database=" + txtFilesUrl.Text + "].[Sheet1$] ";
System.Data.DataTable dt = new System.Data.DataTable();
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "Excel Files(2007以上) (*.xlsx)|*.xlsx|Excel Files(2000-2003) (*.xls)|*.xls";
try
{
string filename = txtFilesUrl.Text;
//string sql = "insert into main_body select * from [Excel 8.0;HDR=Yes;IMEX=1;database=" + txtFilesUrl.Text + "].[Sheet1$] ";
+ "','" + dt.Rows[i]["职位层次"].ToString()
+ "','" + dt.Rows[i]["工作单位及职务"].ToString() + "','" + dt.Rows[i]["技术职务"].ToString()
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
this.txtFilesUrl.Text = openFileDialog1.FileName;
this.btnSelectFile.Enabled = false;
}
return names;
}
/// <summary>
/// 开始导入
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnImport_Click(object sender, EventArgs e)
{
if (txtFilesUrl.Text.Length == 0)
{
MessageBoxEx.Show("请选择导入数据的Execl文件");
}
else
{
OleDbConnection conExcel = new OleDbConnection();
/// <param name="sender"></param>
/// <param name="e"></param>
Microsoft.Office.Interop.Excel.Workbook wb = wbs.Open(filePath, Type.Missing, Type.Missห้องสมุดไป่ตู้ng, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
{
for (int i = 0; i < dt.Rows.Count; i++)
{
//写入数据库数据
{
conExcel.Close();
}
}
}
/// <summary>
/// //导出到execl
/// </summary>
this.txtFilesUrl.ReadOnly = true;
}
}
/// <summary>
/// 获得当前所选择的Excel Sheet的所有名字
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static string[] GetExcelSheetNames(string filePath)
{
}
//OleDbCommand com = new OleDbCommand(sql, conExcel);
//conExcel.Open();
//com.ExecuteNonQuery();
//DbHelperOleDb.ExecuteSql(sql);
//MessageBoxEx.Show("导入数据成功", "导入数据", MessageBoxButtons.OK, rmation);
+ "','" + dt.Rows[i]["考官类别"].ToString()
+ "')";
DbHelperOleDb.ExecuteSql(MySql);
string MySql = "insert into Main_Body values(" + DbHelperOleDb.GetMaxID("oae001", "main_body") + ",'" + dt.Rows[i]["姓名"].ToString() + "','" + dt.Rows[i]["性别"].ToString()
/// <summary>
/// 选择文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSelectFile_Click(object sender, EventArgs e)
Microsoft.Office.Interop.Excel.ApplicationClass excelApp = new ApplicationClass();
Microsoft.Office.Interop.Excel.Workbooks wbs = excelApp.Workbooks;
this.txtFilesUrl.Text = "";
this.txtFilesUrl.ReadOnly = false;
this.btnSelectFile.Enabled = true;
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
//openFileDialog1.CreatePrompt = true;
openFileDialog1.Title = "导入文件路径";
}
catch (Exception ex)
{
MessageBoxEx.Show(ex.ToString());
}
finally
Type.Missing, Type.Missing, Type.Missing, Type.Missing);
int count = wb.Worksheets.Count;
string[] names = new string[count];
+ "','" + dt.Rows[i]["移动电话"].ToString()
+ "','" + dt.Rows[i]["办公电话"].ToString()