//打开文件窗体选择excel文件
public static string Open(string filename)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = “Excel(.xlsx)|.xlsx|All File(.)|.”;
dialog.Title = “打开”;
dialog.RestoreDirectory = true;
dialog.FileName = filename;
string result;
if (dialog.ShowDialog() == DialogResult.OK)
{
result = dialog.FileName;
}
else
{
result = string.Empty;
}
return result;
}
//拿到excel里面的数据,如果有图片就加上第三个方法(InsertPicturesIntoDataTable)
public static bool ExcelFileToDataTable(string filepath, out System.Data.DataTable datatable, bool exportColumnName, out string error)
{
error = “”;
datatable = null;
bool result;
try
{
if (!System.IO.File.Exists(filepath))
{
error = “文件不存在”;
datatable = null;
result = false;
}
else
{
Workbook workbook = new Workbook(filepath);
Worksheet worksheet = workbook.Worksheets[0];
datatable = worksheet.Cells.ExportDataTable(0, 0, worksheet.Cells.MaxRow + 1, worksheet.Cells.MaxColumn + 1, exportColumnName);
Aspose.Cells.Drawing.PictureCollection pictures = worksheet.Pictures;
if (pictures.Count > 0)
{
string error2 = “”;
if (InsertPicturesIntoDataTable(pictures, datatable, out datatable, out error2) == false)
{
error = error + error2;
}
}
datatable.TableName = worksheet.Name;
result = true;
}
}
catch (System.Exception e)
{
error = e.Message;
result = false;
}
return result;
}
//把图片插入到相应的gridcontrol的表格中
private static bool InsertPicturesIntoDataTable(Aspose.Cells.Drawing.PictureCollection pictures, DataTable fromdatatable, out DataTable datatable, out string error)
{
error = “”;
datatable = fromdatatable;
datatable.Columns.Add(“orImg”,typeof(Image));
//把图片按位置插入Table中
DataRow[] rows = datatable.Select();
foreach (Aspose.Cells.Drawing.Picture picture in pictures)
{
try
{
System.Console.WriteLine(picture.GetType().ToString());
//----把图片转换成System.Drawing.Image----
MemoryStream mstream = new MemoryStream();
mstream.Write(picture.Data, 0, picture.Data.Length);
System.Drawing.Image image = System.Drawing.Image.FromStream(mstream);
//----Image放入DataTable------
//datatable.Columns[picture.UpperLeftColumn].DataType = image.GetType();
rows[picture.UpperLeftRow-1][“orImg”] = image;
}
catch (System.Exception e)
{
error = error + " InsertPicturesIntoDataTable: " + e.Message;
}
}
return true;
}
//** 注意: 项目引用一个插件Aspose.Cells的插件