using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.IO;
using System.Text;
using System.Web;
using NPOI.HPSF;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;
using System.Data.Common;
using System.Data.SqlClient;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using CommonLib;
using DevExpress.XtraEditors.Repository;
using Lskj.PubUtils;
using ControlLib.inh;
using Lskj.MyControl.LookUp;
using Lskj.MyControl;
using Lskj.Excel;
namespace ExcelPlus
{
public class ExcelHelper
{
///
/// DataTable导出到Excel文件
///
/// 源DataTable
/// 表头文本
/// 保存位置
/// 工作表名称
/// 柳永法 http://www.yongfa365.com/ 2010-5-8 22:21:41
public static void Export(DataTable dtSource, string strHeaderText, string strFileName, string strSheetName, string[] oldColumnNames, string[] newColumnNames)
{
if (strSheetName == "")
{
strSheetName = "Sheet";
}
using (MemoryStream ms = Export(dtSource, strHeaderText, strSheetName, oldColumnNames, newColumnNames))
{
using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
{
byte[] data = ms.ToArray();
fs.Write(data, 0, data.Length);
fs.Flush();
}
}
}
///
/// DataTable导出到Excel的MemoryStream
///
/// 源DataTable
/// 表头文本
/// 工作表名称
/// 柳永法 http://www.yongfa365.com/ 2010-5-8 22:21:41
public static MemoryStream Export(DataTable dtSource, string strHeaderText, string strSheetName, string[] oldColumnNames, string[] newColumnNames)
{
if (oldColumnNames.Length != newColumnNames.Length)
{
return new MemoryStream();
}
HSSFWorkbook workbook = new HSSFWorkbook();
//HSSFSheet sheet = workbook.CreateSheet();// workbook.CreateSheet();
ISheet sheet = workbook.CreateSheet(strSheetName);
#region 右击文件 属性信息
{
DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
dsi.Company = "朗速科技";
workbook.DocumentSummaryInformation = dsi;
SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
if (HttpContext.Current.Session["realname"] != null)
{
si.Author = HttpContext.Current.Session["realname"].ToString();
}
else
{
if (HttpContext.Current.Session["username"] != null)
{
si.Author = HttpContext.Current.Session["username"].ToString();
}
} //填加xls文件作者信息
si.ApplicationName = "朗速ERP"; //填加xls文件创建程序信息
si.LastAuthor = "dingliang"; //填加xls文件最后保存者信息
si.Comments = "朗速ERP导出文件"; //填加xls文件作者信息
si.Title = strHeaderText; //填加xls文件标题信息
si.Subject = strHeaderText; //填加文件主题信息
si.CreateDateTime = DateTime.Now;
workbook.SummaryInformation = si;
}
#endregion
ICellStyle dateStyle = workbook.CreateCellStyle();
IDataFormat format = workbook.CreateDataFormat();
dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
#region 取得列宽
int[] arrColWidth = new int[oldColumnNames.Length];
for (int i = 0; i < oldColumnNames.Length; i++)
{
arrColWidth[i] = Encoding.GetEncoding(936).GetBytes(newColumnNames[i]).Length;
}
/*
foreach (DataColumn item in dtSource.Columns)
{
arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;
}
* */
for (int i = 0; i < dtSource.Rows.Count; i++)
{
for (int j = 0; j < oldColumnNames.Length; j++)
{
int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][oldColumnNames[j]].ToString()).Length;
if (intTemp > arrColWidth[j])
{
arrColWidth[j] = intTemp;
}
}
/*
for (int j = 0; j < dtSource.Columns.Count; j++)
{
int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;
if (intTemp > arrColWidth[j])
{
arrColWidth[j] = intTemp;
}
}
* */
}
#endregion
int rowIndex = 0;
foreach (DataRow row in dtSource.Rows)
{
#region 新建表,填充表头,填充列头,样式
if (rowIndex == 65535 || rowIndex == 0)
{
if (rowIndex != 0)
{
sheet = workbook.CreateSheet(strSheetName + ((int)rowIndex / 65535).ToString());
}
#region 表头及样式
{
IRow headerRow = sheet.CreateRow(0);
headerRow.HeightInPoints = 25;
headerRow.CreateCell(0).SetCellValue(strHeaderText);
ICellStyle headStyle = workbook.CreateCellStyle();
headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
IFont font = workbook.CreateFont();
font.FontHeightInPoints = 20;
font.Boldweight = 700;
headStyle.SetFont(font);
headerRow.GetCell(0).CellStyle = headStyle;
//sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1));
sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, dtSource.Columns.Count - 1));
}
#endregion
#region 列头及样式
{
//HSSFRow headerRow = sheet.CreateRow(1);
IRow headerRow = sheet.CreateRow(1);
ICellStyle headStyle = workbook.CreateCellStyle();
headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
IFont font = workbook.CreateFont();
font.FontHeightInPoints = 10;
font.Boldweight = 700;
headStyle.SetFont(font);
for (int i = 0; i < oldColumnNames.Length; i++)
{
headerRow.CreateCell(i).SetCellValue(newColumnNames[i]);
headerRow.GetCell(i).CellStyle = headStyle;
//设置列宽
sheet.SetColumnWidth(i, (arrColWidth[i] + 1) * 256);
}
/*
foreach (DataColumn column in dtSource.Columns)
{
headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
headerRow.GetCell(column.Ordinal).CellStyle = headStyle;
//设置列宽
sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
}
* */
}
#endregion
rowIndex = 2;
}
#endregion
#region 填充内容
IRow dataRow = sheet.CreateRow(rowIndex);
//foreach (DataColumn column in dtSource.Columns)
for (int i = 0; i < oldColumnNames.Length; i++)
{
ICell newCell = dataRow.CreateCell(i);
string drValue = row[oldColumnNames[i]].ToString();
switch (dtSource.Columns[oldColumnNames[i]].DataType.ToString())
{
case "System.String"://字符串类型
newCell.SetCellValue(drValue);
break;
case "System.DateTime"://日期类型
DateTime dateV;
DateTime.TryParse(drValue, out dateV);
newCell.SetCellValue(dateV);
newCell.CellStyle = dateStyle;//格式化显示
break;
case "System.Boolean"://布尔型
bool boolV = false;
bool.TryParse(drValue, out boolV);
newCell.SetCellValue(boolV);
break;
case "System.Int16"://整型
case "System.Int32":
case "System.Int64":
case "System.Byte":
int intV = 0;
int.TryParse(drValue, out intV);
newCell.SetCellValue(intV);
break;
case "System.Decimal"://浮点型
case "System.Double":
double doubV = 0;
double.TryParse(drValue, out doubV);
newCell.SetCellValue(doubV);
break;
case "System.DBNull"://空值处理
newCell.SetCellValue("");
break;
default:
newCell.SetCellValue("");
break;
}
}
#endregion
rowIndex++;
}
using (MemoryStream ms = new MemoryStream())
{
workbook.Write(ms);
ms.Flush();
ms.Position = 0;
//sheet.Dispose();
sheet = null;
workbook = null;
//workbook.Dispose();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheet
return ms;
}
}
///
/// 从表格中读取数据到Excel
///
/// 需要导出的表格
///
public static int ExportGrid(DevExpress.XtraGrid.GridControl GridControlPub)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Title = "导出Excel";
saveFileDialog.Filter = "Excel文件(*.xls)|*.xls|Excel2007|*.xlsx|PDF文件|*.PDF|RTF文件|*.RTF|HTML文件|*.html";
DialogResult dialogResult = saveFileDialog.ShowDialog();
if (dialogResult == DialogResult.OK)
{
DevExpress.XtraPrinting.XlsExportOptions options = new DevExpress.XtraPrinting.XlsExportOptions();
if (saveFileDialog.FilterIndex == 1)
{
GridControlPub.ExportToXls(saveFileDialog.FileName);
}
if (saveFileDialog.FilterIndex == 2)
{
GridControlPub.ExportToXlsx(saveFileDialog.FileName);
}
if (saveFileDialog.FilterIndex == 3)
{
GridControlPub.ExportToPdf(saveFileDialog.FileName);
}
if (saveFileDialog.FilterIndex == 4)
{
GridControlPub.ExportToRtf(saveFileDialog.FileName);
}
if (saveFileDialog.FilterIndex == 5)
{
GridControlPub.ExportToHtml(saveFileDialog.FileName);
}
DevExpress.XtraEditors.XtraMessageBox.Show("保存成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return 1;
}
///
/// WEB导出DataTable到Excel
///
/// 源DataTable
/// 表头文本
/// 文件名
/// 柳永法 http://www.yongfa365.com/ 2010-5-8 22:21:41
public static void ExportByWeb(DataTable dtSource, string strHeaderText, string strFileName)
{
ExportByWeb(dtSource, strHeaderText, strFileName, "sheet");
}
///
/// WEB导出DataTable到Excel
///
/// 源DataTable
/// 表头文本
/// 输出文件名,包含扩展名
/// 要导出的DataTable列数组
/// 导出后的对应列名
public static void ExportByWeb(DataTable dtSource, string strHeaderText, string strFileName, string[] oldColumnNames, string[] newColumnNames)
{
ExportByWeb(dtSource, strHeaderText, strFileName, "sheet", oldColumnNames, newColumnNames);
}
///
/// WEB导出DataTable到Excel
///
/// 源DataTable
/// 表头文本
/// 输出文件名
/// 工作表名称
public static void ExportByWeb(DataTable dtSource, string strHeaderText, string strFileName, string strSheetName)
{
HttpContext curContext = HttpContext.Current;
// 设置编码和附件格式
curContext.Response.ContentType = "application/vnd.ms-excel";
curContext.Response.ContentEncoding = Encoding.UTF8;
curContext.Response.Charset = "";
curContext.Response.AppendHeader("Content-Disposition",
"attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8));
//生成列
string columns = "";
for (int i = 0; i < dtSource.Columns.Count; i++)
{
if (i > 0)
{
columns += ",";
}
columns += dtSource.Columns[i].ColumnName;
}
curContext.Response.BinaryWrite(Export(dtSource, strHeaderText, strSheetName, columns.Split(','), columns.Split(',')).GetBuffer());
curContext.Response.End();
}
///
/// 导出DataTable到Excel
///
/// 要导出的DataTable
/// 标题文字
/// 文件名,包含扩展名
/// 工作表名
/// 要导出的DataTable列数组
/// 导出后的对应列名
public static void ExportByWeb(DataTable dtSource, string strHeaderText, string strFileName, string strSheetName, string[] oldColumnNames, string[] newColumnNames)
{
HttpContext curContext = HttpContext.Current;
// 设置编码和附件格式
curContext.Response.ContentType = "application/vnd.ms-excel";
curContext.Response.ContentEncoding = Encoding.UTF8;
curContext.Response.Charset = "";
curContext.Response.AppendHeader("Content-Disposition",
"attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8));
curContext.Response.BinaryWrite(Export(dtSource, strHeaderText, strSheetName, oldColumnNames, newColumnNames).GetBuffer());
curContext.Response.End();
}
/// 读取excel
/// 默认第一行为表头,导入第一个工作表
///
/// excel文档路径
///
public static DataTable Import(string strFileName)
{
DataTable dt = new DataTable();
HSSFWorkbook hssfworkbook = null;
try
{
using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
{
hssfworkbook = new HSSFWorkbook(file);
}
}
catch (InvalidOperationException)
{
XtraMessageBox.Show("请删除文件最后一行统计行.");
return dt;
}
catch (IOException)
{
XtraMessageBox.Show("文件[" + strFileName + "] \r\n处于打开状态,请关闭后在读取文件.");
return dt;
}
ISheet sheet = hssfworkbook.GetSheetAt(0);
System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
IRow headerRow = sheet.GetRow(0);
int cellCount = headerRow.LastCellNum;
try
{
for (int j = 0; j < cellCount; j++)
{
ICell cell = headerRow.GetCell(j);
dt.Columns.Add(cell + "");
}
for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i);
if (row == null) continue;
DataRow dataRow = dt.NewRow();
for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j) != null)
{
if ((row.GetCell(j).CellType == CellType.Numeric) && (row.GetCell(j).ToString().IndexOf('-') != -1) && (row.GetCell(j).ToString()[0] != '-'))
dataRow[j] = row.GetCell(j).DateCellValue;
else
if (row.GetCell(j).CellType == CellType.Numeric)
dataRow[j] = row.GetCell(j).NumericCellValue;
else
{
ICell cell = row.GetCell(j);
IRichTextString richTextString = (IRichTextString)cell.RichStringCellValue;
string cellValue = string.Empty;
for (int m = 0; m < richTextString.Length; m++)
{
IFont font = sheet.Workbook.GetFontAt(richTextString.GetFontAtIndex(m));
string str = string.Empty;
string code= richTextString.ToString().Substring(m,1);
switch (font.TypeOffset)
{
case FontSuperScript.Sub:
str = ChemistryHelper.GetSubChar(code);
break;
case FontSuperScript.Super:
str = ChemistryHelper.GetSuperChar(code);
break;
default:
str = code;
break;
}
cellValue = cellValue + str;
}
cell.SetCellValue(cellValue);
dataRow[j] = cell + "";
//dataRow[j] = row.GetCell(j) + "";
}
}
}
dt.Rows.Add(dataRow);
}
}
catch (Exception ex)
{
}
return dt;
}
public static DataTable Import(string strFileName, DataTable dt)
{
//DataTable dt = new DataTable();
int firstCell = dt.Columns.Count;
//MessageBox.Show(firstCell.ToString());
HSSFWorkbook hssfworkbook;
using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
{
hssfworkbook = new HSSFWorkbook(file);
}
ISheet sheet = hssfworkbook.GetSheetAt(0);
System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
IRow headerRow = sheet.GetRow(0);
int cellCount = headerRow.LastCellNum;
for (int j = 0; j < cellCount; j++)
{
ICell cell = headerRow.GetCell(j);
dt.Columns.Add(cell.ToString());
}
for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i);
DataRow dataRow = dt.NewRow();
for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j) != null)
{
if (row.GetCell(j).CellType == CellType.Numeric)
dataRow[j + firstCell] = row.GetCell(j).NumericCellValue;
else
dataRow[j + firstCell] = row.GetCell(j).ToString();
}
}
dt.Rows.Add(dataRow);
}
return dt;
}
private static GridColumn getColumnByTitle(string title,GridView gridView)
{
GridColumn gc = null;
foreach (GridColumn item in gridView.Columns)
{
if (item.Caption.Equals(title))
{
gc = item;
break;
}
}
return gc;
}
public static void ImportByColumn(string strFileName, GridView gridView, Dictionary lookupDataSet,Panel parentPanel=null)
{
List lsTitle = new List();
HSSFWorkbook hssfworkbook;
using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
{
hssfworkbook = new HSSFWorkbook(file);
}
ISheet sheet = hssfworkbook.GetSheetAt(0);
System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
IRow headerRow = sheet.GetRow(0);
int cellCount = headerRow.LastCellNum;
for (int j = 0; j < cellCount; j++)
{
ICell cell = headerRow.GetCell(j);
lsTitle.Add(cell.ToString());
}
if (lsTitle.Count < 1)
{
MessageBox.Show("Excel文件中没有找到需要导入的列");
return;
}
try
{
for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
{
gridView.AddNewRow();
IRow row = sheet.GetRow(i);
for (int j = row.FirstCellNum; j < cellCount; j++)
{
if ((row.GetCell(j) != null) && (row.GetCell(j).ToString() != ""))
{
GridColumn col = getColumnByTitle(lsTitle[j].ToString(), gridView);
if (col != null)
{
RepositoryItemSearchLookUpEdit lookup = col.ColumnEdit as RepositoryItemSearchLookUpEdit;
RepositoryItemLookUpEdit lookup1 = col.ColumnEdit as RepositoryItemLookUpEdit;
string tmpkey = "";
string tmpvalue = "";
if ((lookup != null) || (lookup1 != null))
{
if (lookup != null)
{
tmpkey = lookup.ValueMember;
tmpvalue = lookup.DisplayMember;
}
else
{
tmpkey = lookup1.ValueMember;
tmpvalue = lookup1.DisplayMember;
}
DataRow[] tmpdr = null;
if ((lookupDataSet[col.FieldName].Prefix != "") && (parentPanel != null))
{
string ctlName = lookupDataSet[col.FieldName].Prefix;
ctlName = ctlName.Replace("_parent_","txt_");
Control[] ctl = parentPanel.Controls.Find(ctlName, true);
string pKey = "";
if ((ctl!=null) &&(ctl.Length>0))
pKey = GetControlText(ctl[0]);
tmpdr = lookupDataSet[col.FieldName].Select(tmpvalue + "='" + row.GetCell(j).ToString() + "' and " + lookupDataSet[col.FieldName].Prefix + "='" + pKey + "'");
}
else
tmpdr = lookupDataSet[col.FieldName].Select(tmpvalue + "='" + row.GetCell(j).ToString() + "'");
if ((tmpdr != null) && (tmpdr.Length > 0))
gridView.SetFocusedRowCellValue(col, tmpdr[0][tmpkey] + "");
}
else
{
if (row.GetCell(j).ToString() == "校验")
gridView.SetFocusedRowCellValue(col, "1");
else if (row.GetCell(j).ToString() == "非校验")
gridView.SetFocusedRowCellValue(col, "1");
else
gridView.SetFocusedRowCellValue(col, row.GetCell(j).ToString());
}
}
}
}
gridView.PostEditor();
}
}
catch { }
}
///
/// 取指定组件值
///
///
///
public static string GetControlText(Control control)
{
if (control == null)
return "";
if (control.Tag == null)
{
return control.Text;
}
ControlModelTag cmTag = control.Tag as ControlModelTag;
if (cmTag.fieldTypeId == ControlType.LabAutoSeacherText)
{
return control.Text;
}
else if ((cmTag.fieldTypeId == ControlType.LabAutoSeacherValue) ||
(cmTag.fieldTypeId == ControlType.LabComboxValueParam))
{
AutoSearcher te = control as AutoSearcher;
return te.ReturnValue.ToString();
}
else if (cmTag.fieldTypeId == ControlType.LabMultiSelectValue)
{
LabelLookUp lookup = control as LabelLookUp;
return lookup.ReturnValue;
}
else if (cmTag.fieldTypeId == ControlType.LabComboxValue)
{
LabelComboxEx Cb = control as LabelComboxEx;
return Cb.getComboBox.SelectedValue + "";
}
else if (cmTag.fieldTypeId == ControlType.LabComboxText)
{
LabelComboxEx Cb = control as LabelComboxEx;
return Cb.getComboBox.Text;
}
else if (cmTag.fieldTypeId == ControlType.LabDate ||
cmTag.fieldTypeId == ControlType.LabDateTime ||
cmTag.fieldTypeId == ControlType.LabDateTimeShort ||
cmTag.fieldTypeId == ControlType.LabTime ||
cmTag.fieldTypeId == ControlType.LabShortTime)
{
LabelDateEx Cb = control as LabelDateEx;
return Cb.GetDateTimePicker.Value.ToString("yyyy-MM-dd HH:mm:ss");
}
else if (cmTag.fieldTypeId == ControlType.LabTextInt)
{
if ((control.Text.Trim() == ""))
return "0";
else
return control.Text;
}
else
{
if (cmTag.fieldTypeId != 99)
{
return control.Text;
}
}
return "0";
}
public static void ImportByColumn(string strFileName, GridView gridView, Dictionary lookupDataSet, string KeyFieldName, Panel parentPanel = null)
{
if (KeyFieldName.Trim()=="")
{
MessageBox.Show("未指定主键字段,不能更新导入");
return;
}
string KeyFieldCnName = "";
GridColumn keyColumn = gridView.Columns.ColumnByFieldName(KeyFieldName);
if (keyColumn==null)
{
MessageBox.Show("没有找到指定的关键字段,不能更新导入");
return;
}
KeyFieldCnName = keyColumn.Caption;
if (KeyFieldCnName == "")
KeyFieldCnName = KeyFieldName;
List lsTitle = new List();
HSSFWorkbook hssfworkbook;
using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
{
hssfworkbook = new HSSFWorkbook(file);
}
ISheet sheet = hssfworkbook.GetSheetAt(0);
System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
IRow headerRow = sheet.GetRow(0);
int cellCount = headerRow.LastCellNum;
for (int j = 0; j < cellCount; j++)
{
ICell cell = headerRow.GetCell(j);
lsTitle.Add(cell.ToString());
}
if (lsTitle.Count < 1)
{
MessageBox.Show("Excel文件中没有找到需要导入的列,不能更新导入");
return;
}
//MessageBox.Show(KeyFieldCnName);
int KeyFieldIndex = lsTitle.IndexOf(KeyFieldCnName);
if (KeyFieldIndex==-1)
{
MessageBox.Show("Excel文件中没有找到主键列,不能更新导入");
return;
}
try
{
for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
{
//gridView.AddNewRow();
IRow row = sheet.GetRow(i);
object keyValue = row.GetCell(KeyFieldIndex);
if ((keyValue == null)||keyValue.ToString()=="")
{
MessageBox.Show("没有主键值,不能更新导入");
return;
}
if (keyColumn.ColumnType.Name.Contains("Int32"))
{
keyValue = Convert.ToInt32(keyValue.ToString());
}
if (keyColumn.ColumnType.Name.Contains("Int64"))
{
keyValue = Convert.ToInt64(keyValue.ToString());
}
int updRowIndex = gridView.LocateByValue(KeyFieldName, keyValue, null);
if (updRowIndex < 0)
{
MessageBox.Show("没有找到主键["+ keyValue+"],不能更新导入");
return;
}
gridView.SelectRow(updRowIndex);
gridView.FocusedRowHandle = updRowIndex;
for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (j == KeyFieldIndex)
continue;
if ((row.GetCell(j) != null) && (row.GetCell(j).ToString() != ""))
{
GridColumn col = getColumnByTitle(lsTitle[j].ToString(), gridView);
if (col != null)
{
RepositoryItemSearchLookUpEdit lookup = col.ColumnEdit as RepositoryItemSearchLookUpEdit;
RepositoryItemLookUpEdit lookup1 = col.ColumnEdit as RepositoryItemLookUpEdit;
string tmpkey = "";
string tmpvalue = "";
if ((lookup != null) || (lookup1 != null))
{
if (lookup != null)
{
tmpkey = lookup.ValueMember;
tmpvalue = lookup.DisplayMember;
}
else
{
tmpkey = lookup1.ValueMember;
tmpvalue = lookup1.DisplayMember;
}
DataRow[] tmpdr = null;
if ((lookupDataSet[col.FieldName].Prefix != "") && (parentPanel != null))
{
string ctlName = lookupDataSet[col.FieldName].Prefix;
ctlName = ctlName.Replace("_parent_", "txt_");
Control[] ctl = parentPanel.Controls.Find(ctlName, true);
string pKey = "";
if ((ctl != null) && (ctl.Length > 0))
pKey = GetControlText(ctl[0]);
tmpdr = lookupDataSet[col.FieldName].Select(tmpvalue + "='" + row.GetCell(j).ToString() + "' and " + lookupDataSet[col.FieldName].Prefix + "='" + pKey + "'");
}
else
tmpdr = lookupDataSet[col.FieldName].Select(tmpvalue + "='" + row.GetCell(j).ToString() + "'");
//DataRow[] tmpdr = lookupDataSet[col.FieldName].Select(tmpvalue + "='" + row.GetCell(j).ToString() + "'");
if ((tmpdr != null) && (tmpdr.Length > 0))
gridView.SetFocusedRowCellValue(col, tmpdr[0][tmpkey] + "");
}
else
{
if (row.GetCell(j).ToString() == "校验")
gridView.SetFocusedRowCellValue(col, "1");
else if (row.GetCell(j).ToString() == "非校验")
gridView.SetFocusedRowCellValue(col, "1");
else
gridView.SetFocusedRowCellValue(col, row.GetCell(j).ToString());
}
}
}
}
gridView.PostEditor();
}
}
catch { }
}
///
/// 从Excel中获取数据到DataTable
///
/// Excel文件全路径
/// 要保存的实体表名
/// 是否需要提交到数据库
/// 需要导入的表格
///
public static DataTable ImportToGrid(string strFileName, string table, bool apply, GridControl grid)
{
DataTable dtDest = (DataTable)grid.DataSource;
GridView gridV = (GridView)grid.FocusedView;
string fields = "";
if (dtDest == null)
{
dtDest = new DataTable();
foreach (GridColumn gc in gridV.Columns)
{
if (gc.FieldName.Trim() != "")
{
fields = fields + gc.FieldName + ",";
dtDest.Columns.Add(gc.FieldName);
}
}
fields = fields.Substring(0, fields.Length - 1);
}
DataTable dtSource = Import(strFileName);
if (dtSource.Rows.Count < 1)
{
//XtraMessageBox.Show("指定文件没有数据可导入", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return dtDest;
}
foreach (DataRow dr in dtSource.Rows)
{
DataRow dstRow = dtDest.NewRow();
foreach (GridColumn gc in gridV.Columns)
{
try
{
dstRow[gc.FieldName] = dr[gc.Caption];
}
catch (Exception ex)
{
}
}
dtDest.Rows.Add(dstRow);
}
//是否提交数据库
if (apply == true)
{
try
{
string sql = "select " + fields + " from " + table + " where 1<>1";
DbDataAdapter dat = SqlHelper.ExecuteAdapter(CommandType.Text, sql);
SqlCommandBuilder scb = new SqlCommandBuilder((SqlDataAdapter)dat);
DataTable datatb = new DataTable();
dat.Fill(datatb);
dat.Update(dtDest);
dtDest.AcceptChanges();
}
catch (Exception ex)
{
MessageBox.Show("数据提交错误:\n" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
grid.DataSource = dtDest;
return dtDest;
}
///
/// 从Excel中获取数据到DataTable
///
/// Excel文件全路径(服务器路径)
/// 要获取数据的工作表名称
/// 工作表标题行所在行号(从0开始)
///
public static DataTable RenderDataTableFromExcel(string strFileName, string SheetName, int HeaderRowIndex)
{
using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
{
IWorkbook workbook = new HSSFWorkbook(file);
return RenderDataTableFromExcel(workbook, SheetName, HeaderRowIndex);
}
}
///
/// 从Excel中获取数据到DataTable
///
/// Excel文件全路径(服务器路径)
/// 要获取数据的工作表序号(从0开始)
/// 工作表标题行所在行号(从0开始)
///
public static DataTable RenderDataTableFromExcel(string strFileName, int SheetIndex, int HeaderRowIndex)
{
using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
{
IWorkbook workbook = new HSSFWorkbook(file);
string SheetName = workbook.GetSheetName(SheetIndex);
return RenderDataTableFromExcel(workbook, SheetName, HeaderRowIndex);
}
}
///
/// 从Excel中获取数据到DataTable
///
/// Excel文件流
/// 要获取数据的工作表名称
/// 工作表标题行所在行号(从0开始)
///
public static DataTable RenderDataTableFromExcel(Stream ExcelFileStream, string SheetName, int HeaderRowIndex)
{
IWorkbook workbook = new HSSFWorkbook(ExcelFileStream);
ExcelFileStream.Close();
return RenderDataTableFromExcel(workbook, SheetName, HeaderRowIndex);
}
///
/// 从Excel中获取数据到DataTable
///
/// Excel文件流
/// 要获取数据的工作表序号(从0开始)
/// 工作表标题行所在行号(从0开始)
///
public static DataTable RenderDataTableFromExcel(Stream ExcelFileStream, int SheetIndex, int HeaderRowIndex)
{
IWorkbook workbook = new HSSFWorkbook(ExcelFileStream);
ExcelFileStream.Close();
string SheetName = workbook.GetSheetName(SheetIndex);
return RenderDataTableFromExcel(workbook, SheetName, HeaderRowIndex);
}
///
/// 从Excel中获取数据到DataTable
///
/// 要处理的工作薄
/// 要获取数据的工作表名称
/// 工作表标题行所在行号(从0开始)
///
public static DataTable RenderDataTableFromExcel(IWorkbook workbook, string SheetName, int HeaderRowIndex)
{
ISheet sheet = workbook.GetSheet(SheetName);
DataTable table = new DataTable();
try
{
IRow headerRow = sheet.GetRow(HeaderRowIndex);
int cellCount = headerRow.LastCellNum;
for (int i = headerRow.FirstCellNum; i < cellCount; i++)
{
DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
table.Columns.Add(column);
}
int rowCount = sheet.LastRowNum;
#region 循环各行各列,写入数据到DataTable
for (int i = (sheet.FirstRowNum + 1); i < sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i);
DataRow dataRow = table.NewRow();
for (int j = row.FirstCellNum; j < cellCount; j++)
{
ICell cell = row.GetCell(j);
if (cell == null)
{
dataRow[j] = null;
}
else
{
//dataRow[j] = cell.ToString();
switch (cell.CellType)
{
case CellType.Blank:
dataRow[j] = null;
break;
case CellType.Boolean:
dataRow[j] = cell.BooleanCellValue;
break;
case CellType.Numeric:
dataRow[j] = cell.ToString();
break;
case CellType.String:
dataRow[j] = cell.StringCellValue;
break;
case CellType.Error:
dataRow[j] = cell.ErrorCellValue;
break;
case CellType.Formula:
default:
dataRow[j] = "=" + cell.CellFormula;
break;
}
}
}
table.Rows.Add(dataRow);
//dataRow[j] = row.GetCell(j).ToString();
}
#endregion
}
catch (System.Exception ex)
{
table.Clear();
table.Columns.Clear();
table.Columns.Add("出错了");
DataRow dr = table.NewRow();
dr[0] = ex.Message;
table.Rows.Add(dr);
return table;
}
finally
{
//sheet.Dispose();
workbook = null;
sheet = null;
}
#region 清除最后的空行
for (int i = table.Rows.Count - 1; i > 0; i--)
{
bool isnull = true;
for (int j = 0; j < table.Columns.Count; j++)
{
if (table.Rows[i][j] != null)
{
if (table.Rows[i][j].ToString() != "")
{
isnull = false;
break;
}
}
}
if (isnull)
{
table.Rows[i].Delete();
}
}
#endregion
return table;
}
#region 导出Excel
///
/// 导出Excel
///
///
///
public static int SaveXls(DevExpress.XtraGrid.GridControl GridControlPub)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Title = "导出Excel";
saveFileDialog.Filter = "Excel文件(*.xls)|*.xls|Excel2007|*.xlsx|PDF文件|*.PDF|RTF文件|*.RTF|HTML文件|*.html";
DialogResult dialogResult = saveFileDialog.ShowDialog();
if (dialogResult == DialogResult.OK)
{
DevExpress.XtraPrinting.XlsExportOptions options = new DevExpress.XtraPrinting.XlsExportOptions();
if (saveFileDialog.FilterIndex == 1)
{
GridControlPub.ExportToXls(saveFileDialog.FileName);
}
if (saveFileDialog.FilterIndex == 2)
{
GridControlPub.ExportToXlsx(saveFileDialog.FileName);
}
if (saveFileDialog.FilterIndex == 3)
{
GridControlPub.ExportToPdf(saveFileDialog.FileName);
}
if (saveFileDialog.FilterIndex == 4)
{
GridControlPub.ExportToRtf(saveFileDialog.FileName);
}
if (saveFileDialog.FilterIndex == 5)
{
GridControlPub.ExportToHtml(saveFileDialog.FileName);
}
XtraMessageBox.Show("保存成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return 1;
}
#endregion
}
}