C#DataGridView到Excel文件错误

C#DataGridView到Excel文件错误,c#,excel,visual-studio,datasource,C#,Excel,Visual Studio,Datasource,我在youtube教程之后编写了这个代码,在教程中,数据源是一个AOD.NET实体数据模型,我使用了Access数据库。我已经编译了代码,但是出现了各种错误,比如 当前上下文中不存在名称“productBindingSource” 或 当前上下文中不存在名称“DB” 或 找不到类型或命名空间名称“Product” 我不确定我是否错过了添加引用,或者这些错误是否是由于数据源不同造成的 Visual Studio自动添加了//TODO:这行代码等等。,我将其更改为教程中的显示方式 我希望有人能帮我看

我在youtube教程之后编写了这个代码,在教程中,数据源是一个AOD.NET实体数据模型,我使用了Access数据库。我已经编译了代码,但是出现了各种错误,比如

当前上下文中不存在名称“productBindingSource”


当前上下文中不存在名称“DB”


找不到类型或命名空间名称“Product”

我不确定我是否错过了添加引用,或者这些错误是否是由于数据源不同造成的

Visual Studio自动添加了
//TODO:这行代码等等。
,我将其更改为教程中的显示方式

我希望有人能帮我看看我做错了什么

教程:

使用系统;
使用System.Collections.Generic;
使用系统组件模型;
使用系统数据;
使用系统图;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
使用System.Windows.Forms;
命名空间ExportWebsiteData
{
公共部分类Form1:Form
{
公共表格1()
{
初始化组件();
}
私有无效标签1_单击(对象发送方,事件参数e)
{
}
私有void backgroundWorker1\u DoWork(对象发送方,DoWorkEventArgs e)
{
List=((DataParameter)e.Argument).ProductList;
字符串文件名=((数据参数)e.Argument).filename;
Microsoft.Office.Interop.Excel.Application Excel=新的Microsoft.Office.Interop.Excel.Application();
工作簿wb=excel.Workbooks.Add(XlSheetType.xlWorksheet);
工作表ws=(工作表)excel.ActiveSheet;
excel.Visible=false;
int指数=1;
int进程=list.Count;
//添加列
ws.Cells[1,1]=“项目编号”;
ws.cells[1,2]=“模型”;
ws.cells[1,3]=“制造商”;
ws.cells[1,4]=“类别”;
ws.cells[1,5]=“子类别”;
//
foreach(列表中的产品p)
{
如果(!backgroundWorker.CancellationPending)
{
backgroundWorker.ReportProgress(索引+++*100/流程);
ws.Cells[index,1]=p.ItemNumber.ToString();
ws.Cells[index,2]=p.Model.ToString();
ws.Cells[index,3]=p.Manufacturer.ToString();
ws.Cells[index,4]=p.Category.ToString();
ws.Cells[index,5]=p.SubCategory.ToString();
}
}
//保存文件
ws.SaveAs(文件名,XlFileFormat.xlWorkbookdefault,Type.Missing,Type.Missing,true,false,XlSaveConflictResolution.xlLocalSessionChanges,Type.Missing,Type.Missing);
excel.Quit();
}
结构数据参数
{
公共列表产品列表;
公共字符串文件名{get;set;}
}
DataParameter\u inputParameter;
私有void Form1\u加载(对象发送方、事件参数e)
{
使用(this.inventoryTableAdapter.Fill(this._向导_数据_2016_10_17DataSet.Inventory);=new _向导_数据_2016_10_17DataSet())
{
productBindingSource.DataSource=DB.Products.ToList();
}
//TODO:这行代码将数据加载到“\u向导\u数据\u 2016\u 10\u 17DataSet.Inventory”表中。您可以根据需要移动或删除它。
//此.inventoryTableAdapter.Fill(此.u向导\u数据\u 2016\u 10\u 17数据集.Inventory);
}
private void backgroundWorker_ProgressChanged(对象发送方,ProgressChangedEventArgs e)
{
progressBar.Value=e.ProgressPercentage;
lblStatus.Text=string.Format(“处理…{0}”,e.ProgressPercentage);
progressBar.Update();
}
私有void backgroundWorker_RunWorkerCompleted(对象发送方,runworkercompletedeventarge)
{
如果(e.Error==null)
{
睡眠(100);
lblStatus.Text=“您的数据已成功导出。”;
}
}
私有void btnExport_单击(对象发送方,事件参数e)
{
if(backgroundWorker.IsBusy)
返回;
使用(SaveFileDialog sfd=new SaveFileDialog(){Filter=“Excel工作簿|*.xls”})
{
if(sdf.ShowDialog()==DialogResult.OK)
{
_inputParameter.FileName=sfd.FileName;
_inputParameter.ProductList=productBindingSource.DataSource作为列表;
最小进度条=0;
progressBar.Value=0;
backgroundWorker.RunWorkerAsync(\u inputParameter);
}
}
}
}
}
更新:

John的回答确实修复了我的错误,但是数据网格现在由cs代码而不是数据库填充。如果有人能告诉我他们认为问题出在哪里,我已经制作了一个视频来更详细地解释这个问题


从发布的代码中可以看出有几个错误和打字错误。获取数据的
Form1\u Load
方法似乎存在一些问题。为了将其分解,由于使用的数据似乎是
产品
对象的列表,下面的代码使用
产品
对象的
列表
。然后用一些测试数据填充该列表。此测试数据将用作
DataGridView
数据源。数据进入
DataGridView
后,export按钮将成功地将数据从
DataGridView
导出到Excel工作簿

上述张贴代码中的拼写错误:

ws.Cells[1, 1] = "Item Number";
ws.cells[1, 2] = "Model";
单元格列2、3、4、5的小写“C”将抛出定义未找到错误

ws.SaveAs(filename, XlFileFormat.xlWorkbookdefault, ……);
这可能取决于版本,<代码
ws.SaveAs(filename, XlFileFormat.xlWorkbookdefault, ……);
XlFileFormat.xlWorkbookDefault   
SaveFileDialog sfd = new SaveFileDialog()
sdf.ShowDialog()
public class Product {
  public string ItemNumber { get; set; }
  public string Model { get; set; }
  public string Manufacturer { get; set; }
  public string Category { get; set; }
  public string SubCategory { get; set; }

  public Product(string iNum, string model, string manuf, string cat, string subCat) {
    ItemNumber = iNum;
    Model = model;
    Manufacturer = manuf;
    Category = cat;
    SubCategory = subCat;
  }
using Microsoft.Office.Interop.Excel;
using System.Threading;
productBindingSource.DataSource as List<product>;
private void Form1_Load(object sender, EventArgs e)
{
  using (this.inventoryTableAdapter.Fill(this._Wizard_Data_2016_10_17DataSet.Inventory); = new _Wizard_Data_2016_10_17DataSet())
  {
     productBindingSource.DataSource = DB.Products.ToList();
  }
}
private void Form2_Load(object sender, EventArgs e) {
  List<Product> list = GetProductList();
  productBindingSource.DataSource = list;
  dataGridView1.DataSource = productBindingSource;
}
private List<Product> GetProductList() {
  List<Product> products = new List<Product>();
  for (int i = 0; i < 14; i++) {
    products.Add(new Product(i.ToString(), "Model_" + i, "Manufacture_" + i, "Cat_" + i, "SubCat_" + i));
  }
  return products;
}
System.Data.DataTable dt = new System.Data.DataTable();

public Form2() {
  InitializeComponent();
}

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) {
  //List<Product> list = ((DataParameter)e.Argument).ProductList;
  System.Data.DataTable list = ((DataParameter)e.Argument).ProductList;
  string filename = ((DataParameter)e.Argument).FileName;
  Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
  Workbook wb = excel.Workbooks.Add(XlSheetType.xlWorksheet);
  Worksheet ws = (Worksheet)excel.ActiveSheet;
  excel.Visible = false;
  int index = 1;
  //int process = list.Count;
  int process = list.Rows.Count;
  //Add Column
  ws.Cells[1, 1] = "Item Number";
  ws.Cells[1, 2] = "Model";
  ws.Cells[1, 3] = "Manufacturer";
  ws.Cells[1, 4] = "Category";
  ws.Cells[1, 5] = "Subcategory";
   foreach (DataRow dr in list.Rows) {
    if (!backgroundWorker.CancellationPending) {
      backgroundWorker.ReportProgress(index++ * 100 / process);
      ws.Cells[index, 1] = dr.ItemArray[1].ToString();
      ws.Cells[index, 2] = dr.ItemArray[2].ToString();
      ws.Cells[index, 3] = dr.ItemArray[3].ToString();
      ws.Cells[index, 4] = dr.ItemArray[4].ToString();
      ws.Cells[index, 5] = dr.ItemArray[5].ToString();
    }
  }
  //Save file
  ws.SaveAs(filename, XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, true, false, XlSaveConflictResolution.xlLocalSessionChanges, Type.Missing, Type.Missing);
  excel.Quit();
}

struct DataParameter {
  public System.Data.DataTable ProductList;
  public string FileName { get; set; }
}

DataParameter _inputParameter;

private void Form2_Load(object sender, EventArgs e) {
  string ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Test\Test3.accdb";
  using (OleDbConnection olcon = new OleDbConnection(ConnectionString)) {
    using (OleDbDataAdapter adapter = new OleDbDataAdapter()) {

      string command = "SELECT * FROM [Products]";
      //cmd.CommandText = "SELECT * FROM [" + sheetName + "]";

      OleDbCommand cmd = new OleDbCommand(command, olcon);
      //Fill Gridview with Data from Access
      try {
        dt.Clear();
        adapter.SelectCommand = cmd;
        adapter.Fill(dt);
        productBindingSource.DataSource = dt;
        dataGridView1.DataSource = productBindingSource;
      }
      catch (Exception ex) {
        MessageBox.Show(ex.ToString());
      }
      finally {
        olcon.Close();
        var totalWidth = dataGridView1.Columns.GetColumnsWidth(DataGridViewElementStates.None);
      }
    }
  }

}

 private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) {
  progressBar.Value = e.ProgressPercentage;
  lblStatus.Text = string.Format("Processing...{0}", e.ProgressPercentage);
  progressBar.Update();
}

private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
  if (e.Error == null) {
    Thread.Sleep(100);
    lblStatus.Text = "Your data has been successfully exported.";
  }
}

private void btnExport_Click(object sender, EventArgs e) {
  if (backgroundWorker.IsBusy)
    return;
  using (SaveFileDialog sfd = new SaveFileDialog() { Filter = "Excel Workbook|*.xls" }) {
    if (sfd.ShowDialog() == DialogResult.OK) {
      _inputParameter.FileName = sfd.FileName;
      //_inputParameter.ProductList = GetProductsList2();
      _inputParameter.ProductList = (System.Data.DataTable)productBindingSource.DataSource;
      progressBar.Minimum = 0;
      progressBar.Value = 0;
      backgroundWorker.RunWorkerAsync(_inputParameter);
    }
  }
}