我对编程很新。让我们说,我有一个优秀的A列,B列,C列和D列。 我想要的是读取这个excel文件,将所有数据放入datagridview,并从中选择某些列并转移到另一个新的datagridview。
我遇到的问题是我不知道如何从datagridview中放置某些列并将它们转移到另一个新的datagridview。
任何人都可以帮助我!! 请!
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
using Excel = Microsoft.Office.Interop.Excel;
using System.Text.RegularExpressions;
namespace Testing9
{
public partial class ExcelModifer : Form
{
public ExcelModifer()
{
InitializeComponent();
}
private void btnChooseFile_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
this.textBox_path.Text = openFileDialog1.FileName;
LoadExcel();
}
}
private void LoadExcel()
{
OleDbConnection oconn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + textBox_path.Text + ";Extended Properties=\"Excel 8.0;HDR=NO;\";");
oconn.Open();
DataTable dbSchema = oconn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dbSchema == null || dbSchema.Rows.Count < 1)
{
throw new Exception("Error: Could not determine the name of the first worksheet.");
}
string firstSheetName = dbSchema.Rows[0]["TABLE_NAME"].ToString();
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("Select * from [" + firstSheetName + "]", oconn);
DataTable dt = new DataTable();
myDataAdapter.Fill(dt);
dataGridView1.DataSource = dt;
}
private void button1_Click(object sender, EventArgs e)
{
saveFileDialog1.InitialDirectory = "C:";
saveFileDialog1.Title = "Save as Excel File";
saveFileDialog1.FileName = "";
saveFileDialog1.Filter = "Excel Files(2003)|*.xls|Excel Files(2007)|*.xlsx";
if (saveFileDialog1.ShowDialog() != DialogResult.Cancel)
{
Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application();
ExcelApp.Application.Workbooks.Add(Type.Missing);
//Change properties of the Workbook
ExcelApp.Columns.ColumnWidth = 20;
//Storing Each row and column value to excel sheet
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
ExcelApp.Cells[i + 1, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
}
}
ExcelApp.ActiveWorkbook.SaveCopyAs(saveFileDialog1.FileName.ToString());
ExcelApp.ActiveWorkbook.Saved = true;
ExcelApp.Quit();
}
}
}
}
答案 0 :(得分:0)
您可以迭代DataGridViewRows并逐步为您分配值。
foreach (DataGridViewRow row in yourDataGrid.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
// make some assignment in this block.
}
}
答案 1 :(得分:0)
您应该创建另一个数据表并将某个列添加到此数据表,然后将第二个数据绑定到其他gridview。