什么是将460328 – 800328范围内的DataGridView行导出到Excel或sql Server数据库表中而不使用Microsoft Office互操作作为互操作的最快方法是在系统资源上非常缓慢和繁重?
解决方法
对于导出到Excel,如果您不使用基于
XML的2007或2010,Interop几乎是唯一的出路.尽管如此,它并没有它的声誉那么糟糕.我将列出一些解决方案.
1到Excel
首先将Microsoft.Office.Interop.Excel组件引用添加到项目中.这应该在Project中的.NET选项卡下 – >添加参考.
将using语句添加到表单中:
using Excel = Microsoft.Office.Interop.Excel;
private void btnExport_Click(object sender,EventArgs e) { Excel.Application app = new Excel.Application(); app.Visible = true; Excel.Workbook wb = app.Workbooks.Add(1); Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets[1]; // changing the name of active sheet ws.Name = "Exported from gridview"; ws.Rows.HorizontalAlignment = HorizontalAlignment.Center; // storing header part in Excel for (int i = 1; i < dataGridView1.Columns.Count + 1; i++) { ws.Cells[1,i] = dataGridView1.Columns[i - 1].HeaderText; } // storing Each row and column value to excel sheet for (int i = 0; i < dataGridView1.Rows.Count - 1; i++) { for (int j = 0; j < dataGridView1.Columns.Count; j++) { ws.Cells[i + 2,j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString(); } } // sizing the columns ws.Cells.EntireColumn.AutoFit(); // save the application wb.SaveAs("c:\\output.xls",Type.Missing,Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,Type.Missing); // Exit from the application app.Quit(); } }
2 – 到sql Server
这不需要互操作.为了便于使用,将List对象传递给执行插入的事件.如果您将表设置为与网格视图列对应,则很容易.在这里,我使用了一个sproc.
private void btnTosql_Click(object sender,EventArgs e) { string connStr = @"Data Source=(local)\sqlexpress;Initial Catalog=rTALIS;Integrated Security=True"; var cn = new sqlConnection(connStr); var cm = new sqlCommand("exec usp_InsertRecord",cn); cm.CommandType = System.Data.CommandType.StoredProcedure; try { cn.Open(); foreach (Row r in rows) { cm.Parameters.Clear(); cm.Parameters.AddWithValue("@Number1",r.Number1); cm.Parameters.AddWithValue("@Number2",r.Number2); cm.Parameters.AddWithValue("@Number3",r.Number3); cm.Parameters.AddWithValue("@Number4",r.Number4); cm.Parameters.AddWithValue("@Number5",r.Number5); cm.Parameters.AddWithValue("@Number6",r.Number6); cm.Parameters.AddWithValue("@Number7",r.Number7); cm.Parameters.AddWithValue("@Date1",r.Date1); cm.ExecuteNonQuery(); } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { cn.Close(); } }
如果我需要为您调整此信息,请告诉我.在原始示例中,我有List rows = new List();在form_Load方法中声明.这适用于该解决方案,但它的范围现在太有限了.我已将它向上/向上移动到类中,以便可以在窗体上的任何位置调用(特别是btnTosql_Click).我在下面评论过:
List<Row> rows = new List<Row>(); private void Form1_Load(object sender,EventArgs e) { //var rows = new List<Row>(); //limited scope var sr = new StreamReader(@"C:\so_test.txt"); while (!sr.EndOfStream) { string s = sr.ReadLine(); if (!String.IsNullOrEmpty(s.Trim())) { rows.Add(new Row(s)); } } sr.Close(); dataGridView1.DataSource = rows; }