c# - 使用 excel 电子表格作为报表查看器 c# 的数据源

标签 c# excel visual-studio datasource reportviewer

我正在尝试使用 Visual Studio(Windows 窗体应用程序)提供的 reportviewer 创建基于 excel 电子表格的报告。但是,我正在努力寻找阅读/访问电子表格的正确方法。

当我尝试创建新报告时,出现以下窗口:

New report data source

我试过使用对象选项,但没有成功

问题:如何使用 Excel 电子表格创建报告?

我幸运地使用了以下代码来处理该文件,但我找不到将其绑定(bind)到报告查看器的方法:

Excel.Application ExcelObj = new Excel.Application();

this.openFileDialog1.FileName = "*.xls";
if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
{
    Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open(
        openFileDialog1.FileName, 0, true, 5,
        "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false,
        0, true);
    Excel.Sheets sheets = theWorkbook.Worksheets;
    Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);
    for (int i = 1; i <= 10; i++)
    {
        Excel.Range range = worksheet.get_Range("A" + i.ToString(), "J" + i.ToString());
        System.Array myvalues = (System.Array)range.Cells.Value;
        string[] strArray = ConvertToStringArray(myvalues);
    }
}

欢迎任何建议/指导

最佳答案

经过多次谷歌搜索后,我设法将其拼凑在一起并将 Excel 工作表放入基本报告中。

这需要您使用 Excel 电子表格第一行中指定的列名称设置一个数据集,并将该数据集关联到一个报告中。然后您可以使用以下内容来填充它:

[open file dialog code..]
try
{
    string path = this.openFileDialog1.FileName;
    if (Path.GetExtension(path) == ".xls")
    {
        oledbConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"");
    }
    else if (Path.GetExtension(path) == ".xlsx")
    {
        oledbConn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
    }
    oledbConn.Open();

    DataSet ds = new DataSet();

    OleDbCommand cmd = new OleDbCommand();
    cmd.Connection = oledbConn;
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "SELECT * FROM [sheet1$]";

    OleDbDataAdapter oleda = new OleDbDataAdapter();
    oleda = new OleDbDataAdapter(cmd);
    oleda.Fill(ds);
    ds.Tables[0].TableName = "DataTable1";

    this.DataTable1BindingSource.DataSource = ds;
    this.reportViewer1.RefreshReport();
}
catch (Exception ex)
{
}
finally
{
    oledbConn.Close();
}

我发现这些文章很有帮助:

Dyanmic report source

Loading excel into a dataset

关于c# - 使用 excel 电子表格作为报表查看器 c# 的数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21466807/

相关文章:

c# - Windows Phone 8 - 本地化不工作

c++ - Visual C++ 有 __builtin_constant_p() 吗?

c# - Entity Framework 5.0b2 代码优先 : One-To-Many and One-To-One for the same table, 带级联删除

excel - 为 xts 应用函数

javascript - JSON 到 xml 的特殊字符

c++ - 在 C++ 中使用初始化列表时的奇怪行为

c# - CSS 问题 : <hr> line not showing in non-compatibility view in IE 8

c# - ViewModel中的引用ResourceDictionary

c# - 使用 Libtiff.Net 读取 32 位灰度 Tiff

python - 我正在尝试将大学橄榄球队名单抓取到 Excel 文件中,需要帮助组织数据