C#批量导入Excel或WPS实现方法
2014-11-23 11:18
796 查看
批量导入导出Excel,WPS,TXT,可按照系统是否安装OFFICE、WPS情况选择,导出是自动选择。
上效果图
上效果图
/// <summary> /// //获得当前你选择的Excel Sheet的所有名字 /// </summary> /// <param name="filePath">文件路径</param> /// <param name="ExcelType">1 Microsoft Excel 2 WPS Excel</param> /// <returns></returns> public static string[] GetExcelSheetNames(string filePath, int ExcelType) { try { if (ExcelType == 1) { Microsoft.Office.Interop.Excel.ApplicationClass excelApp = new Microsoft.Office.Interop.Excel.ApplicationClass(); Microsoft.Office.Interop.Excel.Workbooks wbs = excelApp.Workbooks; Microsoft.Office.Interop.Excel.Workbook wb = wbs.Open(filePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); int count = wb.Worksheets.Count; string[] names = new string[count]; for (int i = 1; i <= count; i++) { names[i - 1] = ((Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[i]).Name; } return names; } else { ET.Application etApp; ET.workbook etbook; etApp = new ET.Application(); etbook = new ET.workbook(); etbook = (ET.workbook)etApp.Workbooks.Open(filePath, null, null, null, null, null, null, null, null, null, null, null, null); int count = etbook.Worksheets.Count; string[] names = new string[count]; for (int i = 1; i <= count; i++) { names[i - 1] = ((ET.Worksheet)etbook.Worksheets[i]).Name; } return names; } } catch { return null; } } //引用命名空间 using Microsoft.Office.Interop.Excel;WPS的ET /// <summary> /// DataGridView导出文件到Microsoft Excel WPS Excel 文本文档 /// </summary> /// <param name="gridView"></param> /// <param name="excludeColumnsIndexList">排除列"0,1,2"</param> /// <param name="fileName"></param> /// <param name="sheetName"></param> public static void ExportDataGridViewAsExcel(DataGridView gridView, string excludeColumnsIndexList,string fileName, string sheetName) { //导出到execl try { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Microsoft Excel(*.xls)|*.xls|WPS Excel(*.xls)|*.xls|文本文档(*.txt)|*.txt"; saveFileDialog.FileName = fileName; //dataGridView1.Rows[0].Cells[0].Value.ToString() + "幸运榜单_" + DateTime.Now.ToString("yyyymmddhhmmss") + ""; saveFileDialog.FilterIndex = 0; saveFileDialog.RestoreDirectory = true; saveFileDialog.CreatePrompt = true; saveFileDialog.Title = "导出文件保存为"; // saveFileDialog.ShowDialog(); if (saveFileDialog.ShowDialog() == DialogResult.OK) { string strName = saveFileDialog.FileName; if (strName.Length != 0) { int rowscount = gridView.Rows.Count; int colscount = gridView.Columns.Count; if (rowscount <= 0) { MessageBox.Show("无数据需要保存 ", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (colscount <= 0) { MessageBox.Show("无数据需要保存 ", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (saveFileDialog.FilterIndex == 1) { if (rowscount > 65536) { MessageBox.Show("行太多(最大限制为 65536行),不能保存! ", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (colscount > 255) { MessageBox.Show("列太多(最大限制为 255列), 不能保存! ", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } try { //this.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界面。 if (excel == null) { MessageBox.Show("Microsoft Excel无法启动!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); 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; string[,] datas = new string[rowscount + 1, colscount]; int m = 0, n = 0; //生成列名称 这里i是从1开始的 因为我第0列是个隐藏列ID 没必要写进去 for (int i = 0; i < gridView.ColumnCount; i++) { if (("," + excludeColumnsIndexList + ",").IndexOf("," + i.ToString() + ",") == 0) { continue; } if (gridView.Columns[i].Visible) { datas[0, m] = gridView.Columns[i].HeaderText.ToString(); m++; } } //填充数据 for (int i = 0; i < gridView.RowCount; i++) { //j也是从1开始 原因如上 每个人需求不一样 n = 0; for (int j = 0; j < gridView.ColumnCount; j++) { if (("," + excludeColumnsIndexList + ",").IndexOf("," + j.ToString() + ",") == 0) { continue; } if (gridView.Columns[j].Visible) { if (gridView[j, i].Value.GetType() == typeof(string)) { datas[i+1, n] = "'" + gridView[j, i].Value.ToString(); } else { datas[i+1, n] = gridView[j, i].Value.ToString(); } n++; } } //this.toolStripProgressBar1.Value += 100 / gridView.RowCount; } int exportRowCount = rowscount + 1; Microsoft.Office.Interop.Excel.Range range = sheet.get_Range("A1", IndexToColumn(colscount) + exportRowCount.ToString()); range.Value2 = datas; sheet.Columns.EntireColumn.AutoFit(); // Automatically change the column width book.SaveAs(strName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, miss, miss, miss, miss, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, miss, miss, miss, miss, miss); //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); GC.Collect(); } catch (Exception ex) { MessageBox.Show(ex.Message, "导出失败,\n1、如果未安装Microsoft Excel,请导出时尝试选择保存到WPS Excel或者文本文档!\n2、请确保导出到的目标文件未打开,否则程序占用可能导致失败。\n3、如已关闭还提示错误,请尝试在任务管理器结束Excel程序。"); return; } } else if (saveFileDialog.FilterIndex == 2) { if (rowscount > 65536) { MessageBox.Show("行太多(最大限制为 65536行),不能保存! ", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (colscount > 255) { MessageBox.Show("列太多(最大限制为 255列), 不能保存! ", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } try { ET.Application etApp; //获取工作表表格 etApp = new ET.Application(); etApp.Workbooks.Add(Type.Missing); etApp.Visible = false; if (etApp == null) { MessageBox.Show("WPS Excel无法启动!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } System.Reflection.Missing miss = System.Reflection.Missing.Value; ET.Workbooks books = (ET.Workbooks)etApp.Workbooks; ET.workbook book = (ET.workbook)(books.Add(miss)); ET.Worksheet sheet = (ET.Worksheet)book.ActiveSheet; sheet.Name = sheetName; string[,] datas = new string[rowscount + 1, colscount]; int m = 0, n = 0; //生成列名称 这里i是从1开始的 因为我第0列是个隐藏列ID 没必要写进去 for (int i = 0; i < gridView.ColumnCount; i++) { if (("," + excludeColumnsIndexList + ",").IndexOf("," + i.ToString() + ",") == 0) { continue; } if (gridView.Columns[i].Visible) { datas[0, m] = gridView.Columns[i].HeaderText.ToString(); m++; } } //填充数据 for (int i = 0; i < gridView.RowCount; i++) { //j也是从1开始 原因如上 每个人需求不一样 n = 0; for (int j = 0; j < gridView.ColumnCount; j++) { if (("," + excludeColumnsIndexList + ",").IndexOf("," + j.ToString() + ",") == 0) { continue; } if (gridView.Columns[j].Visible) { if (gridView[j, i].Value.GetType() == typeof(string)) { datas[i + 1, n] = "'" + gridView[j, i].Value.ToString(); } else { datas[i + 1, n] = gridView[j, i].Value.ToString(); } n++; } } //this.toolStripProgressBar1.Value += 100 / gridView.RowCount; } int exportRowCount = rowscount + 1; ET.Range range = sheet.get_Range("A1", IndexToColumn(colscount) + exportRowCount.ToString()); range.Value2 = datas; sheet.Columns.EntireColumn.AutoFit(); // Automatically change the column width book.SaveAs(strName, ET.XlFileFormat.xlWorkbookNormal, miss, miss, miss, miss, ET.ETSaveAsAccessMode.etShared, miss, miss, miss, miss); book.Close(false, miss, miss); books.Close(); etApp.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet); System.Runtime.InteropServices.Marshal.ReleaseComObject(book); System.Runtime.InteropServices.Marshal.ReleaseComObject(books); System.Runtime.InteropServices.Marshal.ReleaseComObject(etApp); GC.Collect(); } catch (Exception ex) { MessageBox.Show("导出失败,\n1、如果未安装WPS Excel,请导出时尝试选择保存到Microsoft Excel或者文本文档!\n2、请确保导出到的目标文件未打开,否则程序占用可能导致失败。\n3、如已关闭还提示错误,请尝试在任务管理器结束Excel程序。\n系统消息:" + ex.Message, "错误提示"); return; } } else if (saveFileDialog.FilterIndex == 3) { FileStream fs = new FileStream(strName, FileMode.OpenOrCreate, FileAccess.Write); StreamWriter sw = new StreamWriter(fs); sw.BaseStream.Seek(0, SeekOrigin.End); string str = ""; int n = 0; for (int i = 0; i < gridView.ColumnCount; i++) { if (gridView.Columns[i].Visible) { n++; if (n == 1) { str += gridView.Columns[i].HeaderText.ToString(); } else { str += "," + gridView.Columns[i].HeaderText.ToString(); } } } sw.WriteLine(str); //填充数据 for (int i = 0; i < gridView.RowCount; i++) { str = ""; int m = 0; //j也是从1开始 原因如上 每个人需求不一样 for (int j = 0; j < gridView.ColumnCount; j++) { if (gridView.Columns[j].Visible) { m++; if (m == 1) { str += gridView[j, i].Value.ToString(); } else { str += "," + gridView[j, i].Value.ToString(); } } } sw.WriteLine(str); //this.toolStripProgressBar1.Value += 100 / gridView.RowCount; } sw.Flush(); sw.Close(); fs.Close(); } MessageBox.Show("数据已经成功导出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; //this.toolStripProgressBar1.Value = 0; //System.Diagnostics.Process.Start(strName); } } } catch (Exception ex) { MessageBox.Show("导出失败,\n1、如果未安装Microsoft Excel或者WPS Excel,请导出时尝试选择保存到文本文档!\n2、请确保导出到的目标文件未打开,否则程序占用可能导致失败。\n3、如已关闭还提示错误,请尝试在任务管理器结束Excel程序。\n系统消息:" + ex.Message, "错误提示"); return; } } //引用命名空间 using Microsoft.Office.Interop.Excel;WPS的ET /// <summary> /// DataTable导出文件到Microsoft Excel WPS Excel 文本文档 /// </summary> /// <param name="dt"></param> /// <param name="fileName"></param> /// <param name="sheetName"></param> public static void ExportDataTableAsExcel(System.Data.DataTable dt, string fileName, string sheetName) { //导出到execl try { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Microsoft Excel(*.xls)|*.xls|WPS Excel(*.xls)|*.xls|文本文档(*.txt)|*.txt"; saveFileDialog.FileName = fileName; //dataGridView1.Rows[0].Cells[0].Value.ToString() + "幸运榜单_" + DateTime.Now.ToString("yyyymmddhhmmss") + ""; saveFileDialog.FilterIndex = 0; saveFileDialog.RestoreDirectory = true; saveFileDialog.CreatePrompt = true; saveFileDialog.Title = "导出文件保存为"; // saveFileDialog.ShowDialog(); if (saveFileDialog.ShowDialog() == DialogResult.OK) { string strName = saveFileDialog.FileName; if (strName.Length != 0) { int rowscount = dt.Rows.Count; int colscount = dt.Columns.Count; if (rowscount <= 0) { MessageBox.Show("无数据需要保存 ", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (colscount <= 0) { MessageBox.Show("无数据需要保存 ", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (saveFileDialog.FilterIndex == 1) { if (rowscount > 65536) { MessageBox.Show("行太多(最大限制为 65536行),不能保存! ", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (colscount > 255) { MessageBox.Show("列太多(最大限制为 255列), 不能保存! ", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } try { //this.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界面。 if (excel == null) { MessageBox.Show("Microsoft Excel无法启动!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); 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; string[,] datas = new string[rowscount + 1, colscount]; //生成列名称 这里i是从1开始的 因为我第0列是个隐藏列ID 没必要写进去 for (int i = 0; i < dt.Columns.Count; i++) { datas[0, i] = dt.Columns[i].ColumnName.Trim(); } //填充数据 for (int i = 0; i < dt.Rows.Count; i++) { //j也是从1开始 原因如上 每个人需求不一样 for (int j = 0; j < dt.Columns.Count; j++) { if (dt.Rows[i][j].GetType() == typeof(string)) { datas[i + 1, j] = "'" + dt.Rows[i][j].ToString(); } else { datas[i + 1, j] = dt.Rows[i][j].ToString(); } } //this.toolStripProgressBar1.Value += 100 / gridView.RowCount; } int exportRowCount = rowscount + 1; Microsoft.Office.Interop.Excel.Range range = sheet.get_Range("A1", IndexToColumn(colscount) + exportRowCount.ToString()); range.Value2 = datas; sheet.Columns.EntireColumn.AutoFit(); // Automatically change the column width book.SaveAs(strName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, miss, miss, miss, miss, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, miss, miss, miss, miss, miss); //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); GC.Collect(); } catch (Exception ex) { MessageBox.Show("导出失败,\n1、如果未安装Microsoft Excel,请导出时尝试选择保存到WPS Excel或者文本文档!\n2、请确保导出到的目标文件未打开,否则程序占用可能导致失败。\n3、如已关闭还提示错误,请尝试在任务管理器结束Excel程序。\n系统消息:" + ex.Message, "错误提示"); return; } } if (saveFileDialog.FilterIndex == 2) { if (rowscount > 65536) { MessageBox.Show("行太多(最大限制为 65536行),不能保存! ", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (colscount > 255) { MessageBox.Show("列太多(最大限制为 255列), 不能保存! ", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } try { ET.Application etApp; //获取工作表表格 etApp = new ET.Application(); etApp.Workbooks.Add(Type.Missing); etApp.Visible = false; if (etApp == null) { MessageBox.Show("WPS Excel无法启动!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } System.Reflection.Missing miss = System.Reflection.Missing.Value; ET.Workbooks books = (ET.Workbooks)etApp.Workbooks; ET.workbook book = (ET.workbook)(books.Add(miss)); ET.Worksheet sheet = (ET.Worksheet)book.ActiveSheet; sheet.Name = sheetName; string[,] datas = new string[rowscount + 1, colscount]; //生成列名称 这里i是从1开始的 因为我第0列是个隐藏列ID 没必要写进去 for (int i = 0; i < dt.Columns.Count; i++) { datas[0, i] = dt.Columns[i].ColumnName.Trim(); } //填充数据 for (int i = 0; i < dt.Rows.Count; i++) { //j也是从1开始 原因如上 每个人需求不一样 for (int j = 0; j < dt.Columns.Count; j++) { if (dt.Rows[i][j].GetType() == typeof(string)) { datas[i + 1, j] = "'" + dt.Rows[i][j].ToString(); } else { datas[i + 1, j] = dt.Rows[i][j].ToString(); } } //this.toolStripProgressBar1.Value += 100 / gridView.RowCount; } int exportRowCount = rowscount + 1; ET.Range range = sheet.get_Range("A1", IndexToColumn(colscount) + exportRowCount.ToString()); range.Value2 = datas; sheet.Columns.EntireColumn.AutoFit(); // Automatically change the column width book.SaveAs(strName, ET.XlFileFormat.xlWorkbookNormal, miss, miss, miss, miss, ET.ETSaveAsAccessMode.etShared, miss, miss, miss, miss); book.Close(false, miss, miss); books.Close(); etApp.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet); System.Runtime.InteropServices.Marshal.ReleaseComObject(book); System.Runtime.InteropServices.Marshal.ReleaseComObject(books); System.Runtime.InteropServices.Marshal.ReleaseComObject(etApp); GC.Collect(); } catch (Exception ex) { MessageBox.Show("导出失败,\n1、如果未安装WPS Excel,请导出时尝试选择保存到Microsoft Excel或者文本文档!\n2、请确保导出到的目标文件未打开,否则程序占用可能导致失败。\n3、如已关闭还提示错误,请尝试在任务管理器结束Excel程序。\n系统消息:" + ex.Message, "错误提示"); return; } } else if (saveFileDialog.FilterIndex == 2) { FileStream fs = new FileStream(strName, FileMode.OpenOrCreate, FileAccess.Write); StreamWriter sw = new StreamWriter(fs); sw.BaseStream.Seek(0, SeekOrigin.End); string str = ""; for (int i = 0; i < dt.Columns.Count; i++) { if (i == 0) { str += dt.Columns[i].ColumnName.Trim(); } else { str += "," + dt.Columns[i].ColumnName.Trim(); } } sw.WriteLine(str); //填充数据 for (int i = 0; i < dt.Rows.Count; i++) { str = ""; //j也是从1开始 原因如上 每个人需求不一样 for (int j = 0; j < dt.Columns.Count; j++) { if (j == 0) { str += dt.Rows[i][j].ToString(); } else { str += "," + dt.Rows[i][j].ToString(); } } sw.WriteLine(str); //this.toolStripProgressBar1.Value += 100 / gridView.RowCount; } sw.Flush(); sw.Close(); fs.Close(); } MessageBox.Show("数据已经成功导出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); //this.toolStripProgressBar1.Value = 0; //System.Diagnostics.Process.Start(strName); } } } catch (Exception ex) { MessageBox.Show(ex.Message, "导出失败,\n1、如果未安装Microsoft Excel或者WPS Excel,请导出时尝试选择保存到文本文档!\n2、请确保导出到的目标文件未打开,否则程序占用可能导致失败。\n3、如已关闭还提示错误,请尝试在任务管理器结束Excel程序。"); } }
相关文章推荐
- [置顶] 关于C++、C#实现EXCEL数据库批量导入数据库万行以上数据效率问题
- Java实现批量导入excel表格数据到数据库中的方法
- 【EXCEL】基于wps的vlookup的数据导入实现方法
- C#实现Excel导入sqlite的方法
- C# 操作EXCEL 类 可以实现导入导出功能 折腾了好长时间 现在两种方法显示出来
- EXTJS学习系列提高篇:第二篇(转载)作者殷良胜,结合EXT2.2+C#.net实现将数据导入Excel的功能
- 实现Excel数据导入到SQL2005中的方法
- c#中高效的excel导入sqlserver的方法
- c#将数据导入Excel另类方法
- c#中高效的excel导入oracle的方法
- 实现Excel数据导入到SQL2005中的方法
- 实现Excel数据批量导入到Access
- 实现Excel数据导入到SQL2005中的方法
- C#导入Excel方法之一
- asp.net/c#代码实现excel to mssql数据导入
- [导入]C#向Excel报表中插入图片的2种方法
- c#中高效的excel导入oracle的方法
- [导入]在C#中启动另一个程序的实现方法[转载]
- EXT2.2+C#.net+Sql 2005实现将数据导入Excel保存
- c#中高效的excel导入sqlserver的方法