トップ回答者
Visual Studio 2017の DataGridViewへ Excelを importする方法

質問
-
VisualStudio2017のDataGridViewへ Excelをimportする方法を教えて下さい。
ExcelDataReder(最新)をインストールしてみましたがうまくいきません。よろしくお願いいたします。
- 編集済み nysky 2017年12月1日 17:06 今まで全く気づかなかったのですが、YouTube動画サイトのスクリーンショットからのコードを、その投稿者の許可なくNetにUpすることは、著作権の侵害に当たるのかもしれないのでコードの部分を削除します。(ふと英語部分だけでGoogleで検索するとTopに表示されたので驚きました)
回答
すべての返信
-
.Net Frameworkの標準ライブラリではないExcelDataReaderというのは何処から拾ってきたものなのでしょう?
nugetでみつかるExcelDataReader v3.2.0ですか?GitHubの最新ブランチですか?
提示されているコードにはnugetの最新だと存在しないプロパティが記述されていて、その部分を修正すれば動きますよ。
「うまくいきません」というのは、どのような結果を望んでいて、現在どのような状態でなのでしょう?<Window x:Class="WpfApp1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApp1" mc:Ignorable="d" Title="MainWindow" Height="350" Width="525"> <DockPanel> <DockPanel DockPanel.Dock="Top" > <Button Click="btnOpen_Click" Content="Open" /> <ComboBox x:Name="cboSheet" SelectionChanged="cboSheet_SelectionChanged"/> </DockPanel> <WindowsFormsHost > <f:DataGridView x:Name="gridView" xmlns:f="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"/> </WindowsFormsHost> </DockPanel> </Window>
using System; using System.Linq; using ExcelDataReader; using System.Data; using System.IO; using System.Windows; using System.Windows.Controls; using System.Windows.Forms; namespace WpfApp1 { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } DataSet result; private void btnOpen_Click(object sender, RoutedEventArgs e) { using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Excel Workbook|*.xls", ValidateNames = true }) { if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { FileStream fs = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read); IExcelDataReader reader = ExcelReaderFactory.CreateBinaryReader(fs); //reader.IsFirstRowAsColumnNames = true;//v3.2.0には存在しないプロパティ ExcelDataSetConfiguration conf = new ExcelDataSetConfiguration(); conf.ConfigureDataTable = (r) => { return new ExcelDataTableConfiguration() { UseHeaderRow = true } ; }; result = reader.AsDataSet(conf); cboSheet.Items.Clear(); foreach (DataTable dt in result.Tables) cboSheet.Items.Add(dt.TableName); reader.Close(); if (cboSheet.Items.Count > 0) { cboSheet.IsDropDownOpen = true; } } } } private void cboSheet_SelectionChanged(object sender, SelectionChangedEventArgs e) { gridView.DataSource = result.Tables[cboSheet.SelectedIndex]; } } }
個別に明示されていない限りgekkaがフォーラムに投稿したコードにはフォーラム使用条件に基づき「MICROSOFT LIMITED PUBLIC LICENSE」が適用されます。(かなり自由に使ってOK!)
- 編集済み gekkaMVP 2017年11月18日 10:50
- 回答の候補に設定 立花楓Microsoft employee, Moderator 2017年11月20日 2:22