第一步:引用:Aspose.Excel.dll
第二步:创建类文件AsposeExcel
代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Aspose.Excel.Cells;
using System.Data;
using System.Windows;
using System.Windows.Forms;
using System.IO;
namespace BIM.Backend.Modules
{
class AsposeExcel
{
private string outFileName = "";
private string fullFilename = "";
private Workbook book = null;
private Worksheet sheet = null;
#region //导入构造数
public AsposeExcel(string fullfilename)
{
fullFilename = fullfilename;
// book = new Workbook();
//book.Open(tempfilename);
//sheet = book.Worksheets[0];
}
#endregion
#region 导入方法
public DataTable ExcelToDatatalbe()
{
Workbook book = new Workbook();
book.Open(fullFilename);
Worksheet sheet = book.Worksheets[];
Cells cells = sheet.Cells;
//获取excel中的数据保存到一个datatable中
DataTable dt_Import = cells.ExportDataTableAsString(, , cells.MaxDataRow + , cells.MaxDataColumn + , false);
// dt_Import.
return dt_Import;
}
#endregion
}
}
导入事件代码:
#region 导入
private void Btn_Click(object sender, RoutedEventArgs e)
{
System.Windows.Forms.OpenFileDialog openFileDlg = new System.Windows.Forms.OpenFileDialog();
openFileDlg.DefaultExt = "xls";
openFileDlg.Filter = "Excel文件(*.xls)|*.xls";
if (openFileDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
DataTable dtI = new AsposeExcel(openFileDlg.FileName).ExcelToDatatalbe();
//将数据保存到数据库
List<SignalRClient.ExcitedInvoking.ExDatagram> __exdatas = new List<SignalRClient.ExcitedInvoking.ExDatagram>();
if (dtI.Rows.Count > )
{
for (int r = ; r < dtI.Rows.Count;r++ )
{
SignalRClient.ExcitedInvoking.ExDatagram __datagram = new SignalRClient.ExcitedInvoking.ExDatagram()
{
OpTableName = "INFO_SBWDGL",
OpType = SignalRClient.ExcitedInvoking.ExDatagram.OpEnum.I,
SortId =
};
__datagram.OpFields.Add("RowGuid");
__datagram.OpParams.Add("@RowGuid", Guid.NewGuid().ToString());
__datagram.OpFields.Add("OperationUserGuid");
__datagram.OpParams.Add("@OperationUserGuid", GlobalRepertories.CurrentLoginUser.RowGuid);
__datagram.OpFields.Add("ZZ");
__datagram.OpParams.Add("@ZZ", GlobalRepertories.CurrentLoginUser.DisplayName);
__datagram.OpFields.Add("ZJXGSJ");
__datagram.OpParams.Add("@ZJXGSJ", DateTime.Now.ToShortDateString());
__datagram.OpFields.Add("ZLSM");
__datagram.OpParams.Add("@ZLSM", Convert.ToString(dtI.Rows[r][]));
__datagram.OpFields.Add("RecordName");
__datagram.OpParams.Add("@RecordName", Convert.ToString(dtI.Rows[r][]));
__datagram.OpFields.Add("DataSource");
__datagram.OpParams.Add("@DataSource", Convert.ToString(dtI.Rows[r][]));
__exdatas.Add(__datagram);
}
SignalRClient.ExcitedInvoking.Transmit(GlobalRepertories.TransmissionEngine, GlobalRepertories.CurrentLoginUser.RowGuid, __exdatas, new SignalRClient.SignalRCallback(
o =>
{
this.Dispatcher.BeginInvoke(new BlankDelegateMethod(() =>
{
MessageBox.Show("数据导入成功!");
dataBind();
})
);
}
)
);
}
}
}
#endregion