반응형

들여올 excel 파일
들여오기 button 클릭 전
들여오기 button 클릭 후

 

[ 방법 ]

1단계 .  들여올 excel 파일 경로 불러오기

2단계 . 가져온 excel 파일 열기

3단계 . excel 파일 안의 원하는 Sheet 에 접근

4단계 . 엑셀의 데이터들을 모델(model)에 담은 후 리스트(list)에 추가하기

5단계 . List에 담겨진 데이터를 Datagrid 에 binding하기

 

[ 소스코드 ]

 

xaml

        <DataGrid x:Name="Datagrid_Import" Grid.Row="1" Grid.ColumnSpan="5" Height="auto" Width="auto" AutoGenerateColumns="False" ItemsSource="{Binding ObserList}" CanUserAddRows = "False" >
                <DataGrid.Resources>
                    <Style TargetType="{x:Type DataGridColumnHeader}">
                        <Setter Property="Background" Value="#464646"/>
                        <Setter Property="FontWeight" Value="SemiBold" />
                        <Setter Property="BorderThickness" Value="0,0,1,2"/>
                        <Setter Property="BorderBrush" Value="Black"/>
                        <Setter Property="Foreground" Value="White" />
                        <Setter Property="HorizontalContentAlignment" Value="Center"/>
                    </Style>
                </DataGrid.Resources>
                <DataGrid.CellStyle>
                    <Style TargetType="DataGridCell">
                        <Setter Property="TextBlock.TextAlignment" Value="Center"/>
                        <Setter Property="IsEditing" Value="true" />
                    </Style>
                </DataGrid.CellStyle>

            <DataGrid.Columns>
                <DataGridTextColumn Header="이름" Width="1.5*" Binding="{Binding ProductName}" IsReadOnly="True"/>
                <DataGridTextColumn Header="수량" Width="*" Binding="{Binding Stock}" IsReadOnly="True"/>
                <DataGridTextColumn Header="제조사" Width="1.5*" Binding="{Binding Manufacture}" IsReadOnly="True"/>
                <DataGridTextColumn Header="입고날짜" Width="2*" Binding="{Binding InputDate, StringFormat = {}{0:yyyy-MM-dd}}" IsReadOnly="True"/>
                <DataGridTextColumn Header="유통기한" Width="2*" Binding="{Binding ExpirationDate, StringFormat = {}{0:yyyy-MM-dd}}" IsReadOnly="True"/>
                <DataGridTextColumn Header="남은기간" Width="1.5*" Binding="{Binding RemainingDate}" IsReadOnly="True"/>
                <DataGridTextColumn Header="관리자" Width="1.5*" Binding="{Binding ManagerNum,Converter={StaticResource ManagerNameConver}}" IsReadOnly="True"/>
                </DataGrid.Columns>
            </DataGrid>        

        <!-- 하단 Export 버튼-->
        <Button x:Name="btn_Import" Grid.Row="2" Grid.Column="4"  Margin="10" Content="들여오기"  Width="95" Height="40"  Background="Gray" HorizontalAlignment="Left" FontWeight="ExtraBold" Foreground="White" Click="Btn_Import_Click"/>

            <!-- 검색창-->
            <StackPanel Grid.ColumnSpan="5" Grid.Row="0" Orientation="Horizontal"  HorizontalAlignment="Center" >
            <Label Width="75" Height="40" Content="파일 이름"  FontSize="15" HorizontalContentAlignment="Center"  VerticalContentAlignment="Center"/>
            <TextBox x:Name="textbox_FileSearch" Width="500" Height="30" TextWrapping="Wrap" VerticalContentAlignment="Center" />
            <Button x:Name ="btn_FileSearch" Content="파일찾기" Height="30" Width="75" Margin="10" FontWeight="ExtraBold" Click="Btn_FileSearch_Click"  />
            </StackPanel>

xaml.cs

        private void Btn_Import_Click(object sender, RoutedEventArgs e)
        {
            // 파일 경로 불러오기
            var fi = new FileInfo(this.textbox_FileSearch.Text);

            //가져온 파일 열기
            using (var package = new ExcelPackage(fi))
            {
                var workbook = package.Workbook;

                //Excel 안의 AllSheet에 접근
                var worksheet = workbook.Worksheets.FirstOrDefault();

                // 시트의 마지막 Row 데이터에서 1빼기
                int noOfRow = worksheet.Dimension.End.Row - 1;

                // 종류 row를 제외하고 2부터 시작하기
                int row = 2;
                List<mProduct> excelData = new List<mProduct>();
                for (int k = 0; k <= noOfRow - 1; k++)
                {
                    mProduct item = new mProduct();
                    item.ProductNumber = Convert.ToInt32(worksheet.GetValue(row, 1));
                    item.ProductName = worksheet.GetValue(row, 2).ToString();
                    item.Stock = Convert.ToInt32(worksheet.GetValue(row, 3));
                    item.Manufacture = worksheet.GetValue(row, 4).ToString();
                    item.InputDate = Convert.ToDateTime(worksheet.GetValue(row, 5).ToString());
                    item.ExpirationDate = Convert.ToDateTime(worksheet.GetValue(row, 6).ToString());
                    item.RemainingDate = Convert.ToInt32(worksheet.GetValue(row, 7));
                    item.ManagerNum = Convert.ToInt32(worksheet.GetValue(row, 8));
                    row++;
                    excelData.Add(item);

                    // productNumber가 0인 시점에서 데이터 불러오는 작업 중단하기
                    if (Convert.ToInt32(worksheet.GetValue(row, 1)) == 0)
                    { break; }
                }
                this.Datagrid_Import.ItemsSource = excelData;
            }
        }

 

반응형

+ Recent posts