赞
踩
using Microsoft.Office.Interop.Excel; using System; using System.Collections.Generic; using System.Data; using System.Data.OleDb; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Util { class ExcelHelper { / 执行SQL查询一个Excel文档的内容 public static System.Data.DataTable ExecuteReader(string fileName, string cmdText, params OleDbParameter[] paramters) { string strCon = " Provider = Microsoft.Jet.OLEDB.4.0; Data Source = " + fileName + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'"; OleDbConnection cn = new OleDbConnection(strCon); OleDbCommand cmd = new OleDbCommand(); OleDbDataReader reader = null; System.Data.DataTable table = new System.Data.DataTable(); try { //cn = new OleDbConnection(strCon); PrepareCommand(cmd, cn, cmdText, paramters); reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); table.Load(reader); cmd.Parameters.Clear(); } finally { if (reader != null) { reader.Close(); reader.Dispose(); } if (cn != null) { cn.Close(); cn.Dispose(); } } return table; } public static System.Data.DataTable GetGridTableInDisplayColumnOrder(DataGridView grid) { var table = new System.Data.DataTable(); var data = grid.DataSource as System.Data.DataTable; if (grid.Columns.Count > 0 && data != null) { var cols = new DataColumn[grid.Columns.Count]; foreach (DataGridViewColumn col in grid.Columns) { cols[col.DisplayIndex] = new DataColumn(col.Name); } table.Columns.AddRange(cols); foreach (DataRow row in data.Rows) { var item = table.NewRow(); foreach (DataColumn col in table.Columns) { item[col.ColumnName] = row[col.ColumnName]; } table.Rows.Add(item); } } return table; } /// <summary> /// 把Excel的某个工作表导入到DataTable中 /// </summary> /// <param name="fileName">文件完整路径</param> /// <param name="sheetName">工作表名</param> /// <param name="HasHeader">是否存在表头。若是会把工作表第一行转成DataTable的列名</param> /// <returns>导入后的DataTable</returns> public static System.Data.DataTable ImportExcel(string fileName,string sheetName, bool HasHeader) { System.Data.DataTable table = ExecuteReader(fileName, "select * from [" + sheetName + "]", null); if (HasHeader) { for (int i = 0; i < table.Columns.Count; i++) table.Columns[i].ColumnName = table.Rows[0][i].ToString(); table.Rows.RemoveAt(0); } return table; } /// <summary> /// 准备OleDbCommand /// </summary> /// <param name="command">查询命令</param> /// <param name="connection">连接类</param> /// <param name="cmdText">命令内容</param> /// <param name="paramters">查询参数</param> private static void PrepareCommand(OleDbCommand command, OleDbConnection connection, string cmdText, params OleDbParameter[] paramters) { command.CommandText = cmdText; command.Connection = connection; if (paramters != null) foreach (OleDbParameter item in paramters) command.Parameters.Add(item); if (connection.State != ConnectionState.Open) connection.Open(); } public static System.Data.DataTable GetDataFromExcelByCom(bool hasTitle = false) { OpenFileDialog openFile = new OpenFileDialog(); openFile.Filter = "Excel(*.xls)|*.xls|Excel(*.xlsx)|*.xlsx"; openFile.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); openFile.Multiselect = false; if (openFile.ShowDialog() == DialogResult.Cancel) return null; var excelFilePath = openFile.FileName; Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Sheets sheets; object oMissiong = System.Reflection.Missing.Value; Microsoft.Office.Interop.Excel.Workbook workbook = null; System.Data.DataTable dt = new System.Data.DataTable(); try { if (app == null) return null; workbook = app.Workbooks.Open(excelFilePath, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong); sheets = workbook.Worksheets; //将数据读入到DataTable中 Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(1);//读取第一张表 if (worksheet == null) return null; int iRowCount = worksheet.UsedRange.Rows.Count; int iColCount = worksheet.UsedRange.Columns.Count; //生成列头 for (int i = 0; i < iColCount; i++) { var name = "column" + i; if (hasTitle) { var txt = ((Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, i + 1]).Text.ToString(); if (!string.IsNullOrWhiteSpace(txt)) name = txt; } while (dt.Columns.Contains(name)) name = name + "_1";//重复行名称会报错。 dt.Columns.Add(new DataColumn(name, typeof(string))); } //生成行数据 Microsoft.Office.Interop.Excel.Range range; int rowIdx = hasTitle ? 2 : 1; for (int iRow = rowIdx; iRow <= iRowCount; iRow++) { DataRow dr = dt.NewRow(); for (int iCol = 1; iCol <= iColCount; iCol++) { range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[iRow, iCol]; dr[iCol - 1] = (range.Value2 == null) ? "" : range.Text.ToString(); } dt.Rows.Add(dr); } return dt; } catch { return null; } finally { workbook.Close(false, oMissiong, oMissiong); System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook); workbook = null; app.Workbooks.Close(); app.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(app); app = null; } } //以下導出Excel方法較慢,行數不多的時候使用 public static bool ToExcel(System.Data.DataTable dt)//少量數據插入 { System.Data.DataTable dataTable = dt; int rowNumber = dataTable.Rows.Count; int rowIndex = 1; int colIndex = 0; if (rowNumber == 0) { return false; } //建立Excel对象 Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); excel.Application.Workbooks.Add(true); excel.Visible = false; //生成字段名称 foreach (System.Data.DataColumn col in dataTable.Columns) { colIndex++; excel.Cells[1, colIndex] = col.ColumnName; } //填充数据 foreach (System.Data.DataRow row in dataTable.Rows) { rowIndex++; colIndex = 0; foreach (System.Data.DataColumn col in dataTable.Columns) { colIndex++; excel.Cells[rowIndex, colIndex] = row[col.ColumnName]; } } excel.Visible = true; return true; } //适合大量数据插入 public static bool ToExcel2(System.Data.DataTable dt) { Microsoft.Office.Interop.Excel.Workbook workbook = null; Microsoft.Office.Interop.Excel.Sheets sheets=null; System.Data.DataTable dataTable = dt; int rowNumber = dataTable.Rows.Count; //int rowIndex = 1; int colIndex = 0; if (rowNumber == 0) { return false; } //建立Excel对象 Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); workbook=excel.Application.Workbooks.Add(true); excel.Visible = false; excel.WindowState = Microsoft.Office.Interop.Excel.XlWindowState.xlMaximized; sheets = workbook.Worksheets; Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(1);//读取第一张表 //生成字段名称 foreach (System.Data.DataColumn col in dataTable.Columns) { colIndex++; excel.Cells[1, colIndex] = col.ColumnName; } //填充数据 //写入数据行 Microsoft.Office.Interop.Excel.Range range,range2; range = worksheet.get_Range("A2", Missing.Value); range = range.get_Resize(dt.Rows.Count, dt.Columns.Count); object[,] cellData = new object[dt.Rows.Count, dt.Columns.Count]; for (int iRow = 0; iRow < dt.Rows.Count; iRow++) { for (int iCol = 0; iCol < dt.Columns.Count; iCol++) { cellData[iRow, iCol] = dt.Rows[iRow][iCol].ToString().Replace("\n", " ").Replace("\t", " "); } } range.set_Value(Missing.Value, cellData); //添加对单元格边框 int Rowcount = worksheet.UsedRange.CurrentRegion.Rows.Count; // range = worksheet.Range[worksheet.Cells[2, 1], worksheet.Cells[Rowcount, dt2.Columns.Count]]; range.Borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous; //設置表頭的格式 range2 = worksheet.Range[worksheet.Cells[1,1],worksheet.Cells[1,dt.Columns.Count]]; range2.Font.Size = 10; range2.Font.Bold = true; range2.Borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous; range2.Cells.Interior.Color = System.Drawing.Color.LightGray; range2.AutoFilter(1); //設置明細格式 range.Font.Size = 10; range.EntireColumn.AutoFit(); //Microsoft.Office.Interop.Excel.XlAutoFilterOperator excel.ActiveWindow.SplitRow = 1; excel.ActiveWindow.SplitColumn = 0; excel.ActiveWindow.FreezePanes = true; excel.Visible = true; excel.WindowState = Microsoft.Office.Interop.Excel.XlWindowState.xlMaximized; return true; } public static bool ToExcel2_2003(System.Data.DataTable dt, string FileName)//少量數據插入 { SaveFileDialog saveFileDialog = new SaveFileDialog(); //设置文件标题 saveFileDialog.Title = "导出Excel文件"; //设置文件类型 saveFileDialog.Filter = "Microsoft Office Excel 工作簿(*.xls)|*.xls"; //设置默认文件类型显示顺序 saveFileDialog.FilterIndex = 1; //是否自动在文件名中添加扩展名 saveFileDialog.AddExtension = true; //是否记忆上次打开的目录 saveFileDialog.RestoreDirectory = true; //设置默认文件名 saveFileDialog.FileName = FileName; //按下确定选择的按钮 if (saveFileDialog.ShowDialog() == DialogResult.OK) { Microsoft.Office.Interop.Excel.Workbook workbook = null; Microsoft.Office.Interop.Excel.Sheets sheets = null; System.Data.DataTable dataTable = dt; int rowNumber = dataTable.Rows.Count; //int rowIndex = 1; int colIndex = 0; if (rowNumber == 0) { return false; } //建立Excel对象 Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); workbook=excel.Application.Workbooks.Add(true); Worksheet ws = (Worksheet)excel.Sheets[1]; ws.Name = "Sheet1"; excel.Visible = false; //excel.WindowState = Microsoft.Office.Interop.Excel.XlWindowState.xlMaximized; sheets = workbook.Worksheets; Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(1);//读取第一张表 //生成字段名称 foreach (System.Data.DataColumn col in dataTable.Columns) { colIndex++; excel.Cells[1, colIndex] = col.ColumnName; } //填充数据 //写入数据行 Microsoft.Office.Interop.Excel.Range range, range2; range = worksheet.get_Range("A2", Missing.Value); range = range.get_Resize(dt.Rows.Count, dt.Columns.Count); object[,] cellData = new object[dt.Rows.Count, dt.Columns.Count]; for (int iRow = 0; iRow < dt.Rows.Count; iRow++) { for (int iCol = 0; iCol < dt.Columns.Count; iCol++) { cellData[iRow, iCol] = dt.Rows[iRow][iCol].ToString().Replace("\n", " ").Replace("\t", " "); } } range.set_Value(Missing.Value, cellData); 添加对单元格边框 //int Rowcount = worksheet.UsedRange.CurrentRegion.Rows.Count; range = worksheet.Range[worksheet.Cells[2, 1], worksheet.Cells[Rowcount, dt2.Columns.Count]]; //range.Borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous; 設置表頭的格式 //range2 = worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[1, dt.Columns.Count]]; //range2.Font.Size = 10; //range2.Font.Bold = true; //range2.Borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous; //range2.Cells.Interior.Color = System.Drawing.Color.LightGray; 設置明細格式 //range.Font.Size = 10; range.EntireColumn.AutoFit(); //excel.ActiveWindow.SplitRow = 1; //excel.ActiveWindow.SplitColumn = 0; //excel.ActiveWindow.FreezePanes = true; //excel.Visible = true; workbook.SaveAs(saveFileDialog.FileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel8, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); excel.Quit(); excel = null; } return true; } //以下導出Excel方法較慢,行數不多的時候使用(標題會自動過濾1,2開始導出) public static bool ToExcelHeaderText(DataGridView dt)//少量數據插入 { System.Data.DataTable dataTable = (dt.DataSource as System.Data.DataTable); int rowNumber = dataTable.Rows.Count; int rowIndex = 1; int colIndex = 0; if (rowNumber == 0) { return false; } //建立Excel对象 Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); excel.Application.Workbooks.Add(true); excel.Visible = false; //写入标题 for (int i = 1; i < dt.ColumnCount; i++) { colIndex++; excel.Cells[1, colIndex] = dt.Columns[i].HeaderText; } //填充数据 foreach (System.Data.DataRow row in dataTable.Rows) { rowIndex++; colIndex = 0; foreach (System.Data.DataColumn col in dataTable.Columns) { colIndex++; excel.Cells[rowIndex, colIndex] = row[col.ColumnName]; } } excel.Visible = true; excel.WindowState = Microsoft.Office.Interop.Excel.XlWindowState.xlMaximized; return true; } public static void ExportDataToExcel(System.Data.DataTable TableName, string FileName)//大量數據流式導出保存 { Exception ex = null; SaveFileDialog saveFileDialog = new SaveFileDialog(); //设置文件标题 saveFileDialog.Title = "导出Excel文件"; //设置文件类型 saveFileDialog.Filter = "Microsoft Office Excel 工作簿(*.xls)|*.xls"; //设置默认文件类型显示顺序 saveFileDialog.FilterIndex = 1; //是否自动在文件名中添加扩展名 saveFileDialog.AddExtension = true; //是否记忆上次打开的目录 saveFileDialog.RestoreDirectory = true; //设置默认文件名 saveFileDialog.FileName = FileName; //按下确定选择的按钮 if (saveFileDialog.ShowDialog() == DialogResult.OK) { //获得文件路径 string localFilePath = saveFileDialog.FileName.ToString(); //数据初始化 int TotalCount; //总行数 int RowRead = 0; //已读行数 int Percent = 0; //百分比 TotalCount = TableName.Rows.Count; //lblStatus.Text = "共有" + TotalCount + "条数据"; //lblStatus.Visible = true; //barStatus.Visible = true; //数据流 System.IO.Stream myStream = saveFileDialog.OpenFile(); StreamWriter sw = new StreamWriter(myStream, Encoding.GetEncoding("utf-8")); string strHeader = ""; //秒钟 //Stopwatch timer = new Stopwatch(); //timer.Start(); try { //写入标题 for (int i = 0; i < TableName.Columns.Count; i++) { if (i > 0) { strHeader += "\t"; } strHeader += TableName.Columns[i].ColumnName.ToString(); } sw.WriteLine(strHeader); //写入数据 //string strData; for (int i = 0; i < TableName.Rows.Count; i++) { RowRead++; Percent = (int)(100 * RowRead / TotalCount); //barStatus.Maximum = TotalCount; //barStatus.Value = RowRead; //lblStatus.Text = "共有" + TotalCount + "条数据,已写入" + Percent.ToString() + "%的数据,共耗时" + timer.ElapsedMilliseconds + "毫秒。"; System.Windows.Forms.Application.DoEvents(); string strData = ""; for (int j = 0; j < TableName.Columns.Count; j++) { if (j > 0) { strData += "\t"; } strData += TableName.Rows[i][j].ToString().Replace("\n"," ").Replace("\t"," "); } sw.WriteLine(strData); } //关闭数据流 sw.Close(); myStream.Close(); //关闭秒钟 //timer.Reset(); //timer.Stop(); //表格自適應 //Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); //excel.Workbooks.Open(saveFileDialog.FileName); //Microsoft.Office.Interop.Excel.Range xlRang = excel.Columns; //xlRang.AutoFit(); //excel.DisplayAlerts = false; //excel.ActiveWorkbook.SaveAs(saveFileDialog.FileName); //excel.ActiveWorkbook.Close(); //excel.Quit(); //读取Excel路徑 //Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); //object missing = System.Type.Missing; //Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks._Open(saveFileDialog.FileName, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing); //Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1]; //excel.Visible = false; //worksheet.Columns.AutoFit();//列宽自适应 //workbook.Save(); //excel.Quit(); } catch (Exception ex1) { ex = ex1; MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { //关闭数据流 sw.Close(); myStream.Close(); //关闭秒钟 //timer.Stop(); //EndBundleExcel(); } if (ex==null) { //成功提示 //if (MessageBox.Show("导出成功,是否立即打开?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) //{ // System.Diagnostics.Process.Start(localFilePath); //} System.Diagnostics.Process.Start(localFilePath); } //赋初始值 //lblStatus.Visible = false; //barStatus.Visible = false; } } public static void ExportDataToExcel(DataGridView dataGridView, string FileName,string Title)//大量數據流式導出保存 { Exception ex = null; SaveFileDialog saveFileDialog = new SaveFileDialog(); //设置文件标题 saveFileDialog.Title = "导出Excel文件"; //设置文件类型 saveFileDialog.Filter = "Microsoft Office Excel 工作簿(*.xls)|*.xls"; //设置默认文件类型显示顺序 saveFileDialog.FilterIndex = 1; //是否自动在文件名中添加扩展名 saveFileDialog.AddExtension = true; //是否记忆上次打开的目录 saveFileDialog.RestoreDirectory = true; //设置默认文件名 saveFileDialog.FileName = FileName; //按下确定选择的按钮 if (saveFileDialog.ShowDialog() == DialogResult.OK) { //获得文件路径 string localFilePath = saveFileDialog.FileName.ToString(); //数据初始化 int TotalCount; //总行数 int RowRead = 0; //已读行数 int Percent = 0; //百分比 TotalCount = dataGridView.Rows.Count; //lblStatus.Text = "共有" + TotalCount + "条数据"; //lblStatus.Visible = true; //barStatus.Visible = true; //数据流 System.IO.Stream myStream = saveFileDialog.OpenFile(); StreamWriter sw = new StreamWriter(myStream, Encoding.GetEncoding("utf-16")); string strHeader = ""; //秒钟 //Stopwatch timer = new Stopwatch(); //timer.Start(); try { if (!string.IsNullOrEmpty(Title)) { sw.WriteLine(Title); } //写入标题 for (int i = 0; i < dataGridView.Columns.Count; i++) { if (i > 0) { strHeader += "\t"; } strHeader += dataGridView.Columns[i].HeaderText.ToString(); } sw.WriteLine(strHeader); //写入数据 //string strData; for (int i=0; i < dataGridView.Rows.Count; i++) { RowRead++; Percent = (int)(100 * RowRead / TotalCount); //barStatus.Maximum = TotalCount; //barStatus.Value = RowRead; //lblStatus.Text = "共有" + TotalCount + "条数据,已写入" + Percent.ToString() + "%的数据,共耗时" + timer.ElapsedMilliseconds + "毫秒。"; System.Windows.Forms.Application.DoEvents(); string strData = ""; for (int j=0; j < dataGridView.Columns.Count; j++) { if (j > 0) { strData += "\t"; } if (dataGridView.Rows[i].Cells[j].Value!=null) { strData += dataGridView.Rows[i].Cells[j].Value.ToString(); } } sw.WriteLine(strData); } //关闭数据流 sw.Close(); myStream.Close(); } catch (Exception ex1) { ex = ex1; MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { //关闭数据流 sw.Close(); myStream.Close(); } if (ex == null) { //成功提示 if (MessageBox.Show("导出成功,是否立即打开?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { System.Diagnostics.Process.Start(localFilePath); } } } } /// <summary> /// 結束excel進程 /// </summary> private static void EndBundleExcel() { GC.Collect(); // 回收资源 System.Diagnostics.Process[] excelProcess = System.Diagnostics.Process.GetProcessesByName("EXCEL"); foreach (var item in excelProcess) { item.Kill(); } } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。