在公司,总有user会提出说我不想把excel中的数据一笔笔维护到后台,今天呢,我就来做个小程式,批量导进excel中的数据,再插进数据库中~
需先选择导进资料到数据库的excel,然后再有个点击确定的按钮,把數據展示到DataGrid,再點擊上傳按鈕添加到數據庫,比较简单
首先,要去下載NPOI,這裡有個地址可以下載~~
http://download.csdn.net/detail/why_n/9858663
建立专案,将下载的文件导进参考~
xaml部分,界面如第一张图
<Window x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="657" Width="1180">
<Grid Height="646">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="310*" />
<ColumnDefinition Width="870*" />
</Grid.ColumnDefinitions>
<TabControl Height="633" HorizontalAlignment="Left" Margin="12,4,0,0" Name="tabControl1" VerticalAlignment="Top" Width="1168" Background="{x:Null}" Grid.ColumnSpan="2">
<TabItem Header=" 批量維護 " FontSize="16">
<Grid Height="598" Width="1158">
<Grid.RowDefinitions>
<RowDefinition Height="358*" />
<RowDefinition Height="240*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="36*" />
<ColumnDefinition Width="263*" />
<ColumnDefinition Width="859*" />
</Grid.ColumnDefinitions>
<DataGrid AutoGenerateColumns="False" BorderBrush="#FF070707" CanUserAddRows="False" FontSize="14" IsReadOnly="True" Margin="10,119,13,0" Name="dgDetail2" SelectionUnit="FullRow" Height="353" VerticalAlignment="Top" Grid.ColumnSpan="3" Grid.RowSpan="2">
<DataGrid.ColumnHeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Control.Background" Value="{StaticResource {x:Static SystemColors.GrayTextBrushKey}}" />
<Setter Property="Control.Foreground" Value="White" />
<Setter Property="Control.FontSize" Value="13" />
<Setter Property="FrameworkElement.Height" Value="30" />
<Setter Property="Control.HorizontalContentAlignment" Value="Center" />
<Setter Property="DataGridColumnHeader.SeparatorBrush" Value="White" />
<Setter Property="Control.BorderThickness" Value="0.5" />
<Setter Property="Control.BorderBrush" Value="Black" />
</Style>
</DataGrid.ColumnHeaderStyle>
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Path=EmpNo}" Header=" 工號 " />
<DataGridTextColumn Binding="{Binding Path=EmpName}" Header=" 姓名 " />
</DataGrid.Columns>
</DataGrid>
<GroupBox FontSize="14" Grid.ColumnSpan="3" Header="匯入文件" Height="103" HorizontalAlignment="Left" Margin="10,10,0,0" Name="groupBox1" VerticalAlignment="Top" Width="1135">
<Grid Height="65">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="102*" />
<ColumnDefinition Width="972*" />
<ColumnDefinition Width="49*" />
</Grid.ColumnDefinitions>
<Button Content="選擇 . . ." FontSize="16" Height="41" HorizontalAlignment="Left" Margin="571,11,0,0" Name="btnSelectPath" VerticalAlignment="Top" Width="130" Grid.Column="1" Click="btnSelectPath_click"/>
<TextBox Background="#FFD4D4D4" FontSize="14" Height="36" HorizontalAlignment="Left" IsReadOnly="True" Margin="10,16,0,0" Name="txtPath" VerticalAlignment="Top" VerticalContentAlignment="Center" Width="540" Grid.Column="1" />
<Button Content="確認上傳" FontSize="16" FontWeight="Normal" Foreground="Black" Height="45" HorizontalAlignment="Right" IsEnabled="False" Margin="0,9,100,0" Name="btnLoad" VerticalAlignment="Top" Width="130" Grid.Column="1" Click="btnLoad_Click" />
<Label Content="文件路徑:" FontSize="16" Height="43" HorizontalAlignment="Left" Margin="23,16,0,0" Name="label3" VerticalAlignment="Top" Grid.ColumnSpan="2" />
</Grid>
</GroupBox>
</Grid>
</TabItem>
</TabControl>
</Grid>
</Window>
代码部分
這裡主要功能就是讀取excel文件,所以插進數據庫的功能就自己實現啦~
namespace WpfApplication3
{
/// <summary>
/// MainWindow.xaml 的互動邏輯
/// </summary>
public partial class MainWindow : Window
{
System.Data.DataTable ls_excleTable;
public MainWindow()
{
InitializeComponent();
}
#region 選擇上傳文件
private void btnSelectPath_click(object sender, RoutedEventArgs e)
{
try
{
OpenFileDialog lo_Dialog = new OpenFileDialog();
lo_Dialog.Filter = "Excel(*.xlsx)|*.xlsx";
lo_Dialog.RestoreDirectory = true;
if (lo_Dialog.ShowDialog() == true)
{
txtPath.Text = lo_Dialog.FileName;
using (NPOI.ReadExcel.ExportExcelHelper a = new NPOI.ReadExcel.ExportExcelHelper(lo_Dialog.FileName))
{
ls_excleTable = a.ExcelToDataTable("工作表1", true);
if (ls_excleTable.Columns.Count != 2)
{
MessageBox.Show("導入表格,欄位不對!");
return;
}
ls_excleTable.Columns[0].ColumnName = "EmpNo"; //姓名
ls_excleTable.Columns[1].ColumnName = "EmpName"; //工號
if (ls_excleTable != null) dgDetail2.ItemsSource = ls_excleTable.DefaultView;
btnLoad.IsEnabled = true;
}
}
}
catch (Exception lo_Ex)
{
btnLoad.IsEnabled = false;
MessageBox.Show("錯誤(btnSelectPath_Click):" + lo_Ex.Message, "", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
#endregion
#region 確認上傳
private void btnLoad_Click(object sender, RoutedEventArgs e)
{
string ls_Msg = "";
bool lv_DTabHead = true;
for (int i = 0; i < ls_excleTable.Rows.Count; i++)
{
/*
该处是插进数据库的动作
*/
}
MessageBox.Show("儲存成功!");
btnLoad.IsEnabled = false;
}
#endregion
}
}
namespace NPOI.ReadExcel
{
public class ExportExcelHelper : IDisposable
{
private string fileName = null; //文件名
private IWorkbook workbook = null;
private FileStream fs = null;
private bool disposed;
public ExportExcelHelper(string fileName)//文件名
{
this.fileName = fileName;
disposed = false;
}
/// <summary>
/// 将DataTable数据导入到excel中
/// </summary>
/// <param name="data">要导入的数据</param>
/// <param name="isColumnWritten">DataTable的列名是否要导入</param>
/// <param name="sheetName">要导入的excel的sheet的名称</param>
/// <returns>导入数据行数(包含列名那一行)</returns>
public int DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten)
{
int i = 0;
int j = 0;
int count = 0;
ISheet sheet = null; // 工作表
fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
if (fileName.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook();
else if (fileName.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook();
try
{
if (workbook != null)
{
sheet = workbook.CreateSheet(sheetName);
}
else
{
return -1;
}
if (isColumnWritten == true) //写入DataTable的列名
{
IRow row = sheet.CreateRow(0);
for (j = 0; j < data.Columns.Count; ++j)
{
row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
}
count = 1;
}
else
{
count = 0;
}
for (i = 0; i < data.Rows.Count; ++i)
{
IRow row = sheet.CreateRow(count);
for (j = 0; j < data.Columns.Count; ++j)
{
row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
}
++count;
}
workbook.Write(fs); //写入到excel
return count;
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
return -1;
}
}
/// <summary>
/// 将excel中的数据导入到DataTable中
/// </summary>
/// <param name="sheetName">excel工作薄sheet的名称</param>
/// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
/// <returns>返回的DataTable</returns>
public DataTable ExcelToDataTable(string sheetName, bool isFirstRowColumn)
{
ISheet sheet = null;
DataTable data = new DataTable();
int startRow = 0;
try
{
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
if (fileName.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook(fs);
else if (fileName.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook(fs);
if (sheetName != null)
{
sheet = workbook.GetSheet(sheetName);
if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
{
sheet = workbook.GetSheetAt(0);
}
}
else
{
sheet = workbook.GetSheetAt(0);
}
if (sheet != null)
{
IRow firstRow = sheet.GetRow(0);
int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
if (isFirstRowColumn)
{
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
ICell cell = firstRow.GetCell(i);
if (cell != null)
{
string cellValue = cell.StringCellValue;
if (cellValue != null)
{
DataColumn column = new DataColumn(cellValue);
data.Columns.Add(column);
}
}
}
startRow = sheet.FirstRowNum + 1;
}
else
{
startRow = sheet.FirstRowNum;
}
//最后一列的标号
int rowCount = sheet.LastRowNum;
for (int i = startRow; i <= rowCount; ++i)
{
IRow row = sheet.GetRow(i);
if (row == null) continue; //没有数据的行默认是null
DataRow dataRow = data.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
{
//dataRow[j] = row.GetCell(j).ToString(); //被下面if代替 XX 只有一行數據
if (row.GetCell(j).CellType == CellType.Numeric && DateUtil.IsCellDateFormatted(row.GetCell(j)))
dataRow[j] = row.GetCell(j).DateCellValue.ToString("yyyy/MM/dd"); //qijiang
else
{
dataRow[j] = row.GetCell(j).ToString();
}
}
}
data.Rows.Add(dataRow);
}
}
return data;
}
catch (Exception ex)
{
throw ex; //qijiang
return null;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
if (fs != null)
fs.Close();
}
fs = null;
disposed = true;
}
}
}
}
具体代码网址:http://download.csdn.net/detail/why_n/9858743