gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:26:33 25 4
gpt4 key购买 nike

我正在尝试使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com