public class ExcelHelper
{
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
protected void Button1_Click(object sender, EventArgs e)
{
var excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
excel.Workbooks.Open("d:\aaa.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
IntPtr t = new IntPtr(excel.Hwnd);
int k = 0;
GetWindowThreadProcessId(t, out k);
System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k);
p.Kill();
}
static Microsoft.Office.Interop.Excel.Application xlApp = null;
static ExcelHelper()
{
}
public static bool InitXl()
{
try
{
if (xlApp == null)
xlApp = new Microsoft.Office.Interop.Excel.Application();// new Microsoft.Office.Interop.Excel.ApplicationClass();
return true;
}
catch (Exception ex)
{
release();
MyMsgBox.ShowError(ex.Message);
}
return false;
}
public bool CreateLine3D(Workbook m_workBook,Range dataRange)
{
//添加一个页面
m_workBook.Charts.Add(Type.Missing, Type.Missing, 1, Type.Missing);
//CreateTitle(int row, int columnbegin, int columnend, string title);
//定义图类型
m_workBook.ActiveChart.ChartType = XlChartType.xlLine;
//图数据源(根据列的索引得到当前绑定列的名称)
m_workBook.ActiveChart.SetSourceData(dataRange, XlRowCol.xlColumns);
//图形宽和高
// m_workBook.ActiveChart.ChartArea.Width = papam.PicWidth;
// m_workBook.ActiveChart.ChartArea.Height = papam.PicHeight;
//表示图示画在SHEET1的,改成自己的SHEET名就好
//m_workSheet.Name = papam.PageName;
m_workBook.ActiveChart.Location(XlChartLocation.xlLocationAsObject,0);
//没有这个标题就出不来
m_workBook.ActiveChart.HasTitle = true;
//报表名称
m_workBook.ActiveChart.ChartTitle.Text = "";
// m_workBook.ActiveChart.ChartArea.Width = papam.PicWidth + CHARTAREAEXCURSION;
// m_workBook.ActiveChart.ChartArea.Height = papam.PicHeight + CHARTAREAEXCURSION;
//图形距离左上角的距离
// m_workBook.ActiveChart.ChartArea.Top = papam.Top;
// m_workBook.ActiveChart.ChartArea.Left = papam.Left;
#region - 定义绘图区 -
//设置绘图区的背景色
// m_workBook.ActiveChart.PlotArea.Interior.ColorIndex = ColorIndex.LightViridity;
//设置绘图区边框线条
// m_workBook.ActiveChart.PlotArea.Border.LineStyle = XlLineStyle.xlLineStyleNone;
// //设置绘图区宽度
// m_workBook.ActiveChart.PlotArea.Width = PLOTAREAWIDTH;
#endregion
#region - 定义X轴 -
//轴样式
Axis xAxis = (Axis)m_workBook.ActiveChart.Axes(XlAxisType.xlCategory, XlAxisGroup.xlPrimary);
//Axis xAxis = (Axis)m_workBook.ActiveChart.Axes(XlAxisType.xlSeriesAxis);
//x轴显示的值
// xAxis.CategoryNames = m_workSheet.get_Range(GetExcelColumnName(papam.XColumn) + papam.XstartRow
// , GetExcelColumnName(papam.XColumn) + papam.XendRow);
// xAxis.HasTitle = true;
// xAxis.AxisTitle.AutoScaleFont = false; //不关掉自动缩放的话后面的字体大小无法设置
// xAxis.AxisTitle.Font.Size = XAXISTITLEFONTSIZE; //X轴标题字体大小
// xAxis.AxisTitle.Text = papam.XAxisName;//X轴名
// xAxis.TickLabels.AutoScaleFont = false;
// xAxis.TickLabels.Font.Size = XAXISTICKLABELSFONTSIZE; //X轴坐标轴字体大小
// xAxis.AxisTitle.Left = papam.PicWidth - m_titleOffset;
#endregion
#region - 定义Y轴 -
//
//
// Axis yAxis = (Axis)m_workBook.ActiveChart.Axes(XlAxisType.xlValue, XlAxisGroup.xlPrimary);
//
//
// yAxis.HasTitle = true;
// yAxis.AxisTitle.AutoScaleFont = false; //不关掉自动缩放的话后面的字体大小无法设置
// yAxis.AxisTitle.Font.Size = YAXISTITLEFONTSIZE; //Y轴标题字体大小
// yAxis.AxisTitle.Text = papam.YAxisName;//Y轴名
// yAxis.TickLabels.AutoScaleFont = false;
// yAxis.TickLabels.Font.Size = YAXISTICKLABELSFONTSIZE; //Y轴坐标轴字体大小
// yAxis.AxisTitle.Top = m_titleOffset;
#endregion
//设置绘图区的数据标志(就是线形顶上出现值)显示出值来
m_workBook.ActiveChart.ApplyDataLabels(XlDataLabelsType.xlDataLabelsShowValue, false, false
, false, false, false, true, false, false, false);
ChartGroup grp = (ChartGroup)m_workBook.ActiveChart.ChartGroups(1);
// grp.GapWidth = CHARTGROUPWIDTH;
//
// m_workBook.ActiveChart.PlotArea.Width = papam.PicWidth - m_titleOffset; //设置绘图区宽度
// m_workBook.ActiveChart.PlotArea.Top = m_titleOffset;
// m_workBook.ActiveChart.PlotArea.Height = papam.PicHeight - m_titleOffset; //设置绘图区高度
// m_workBook.ActiveChart.PlotArea.Left = m_titleOffset;
设置Legend图例的位置和格式
// m_workBook.ActiveChart.HasLegend = false;
return true;
}
static readonly object exportLock = new object();
public static bool ExportExcel(System.Data.DataSet ds, string path, string templateFile, Action
Prc = null)
{
lock (exportLock)
{
bool succeed = false;
if (ds == null && ds.Tables.Count == 0)
return succeed;
Prc.Do("启动Excel...");
if (!InitXl())
return succeed;
// xlApp.Visible = true;
try
{
object objOpt = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Workbook xlBook = null;
try
{
xlBook = xlApp.Workbooks.Open(templateFile, objOpt, true, objOpt, objOpt, objOpt, true, objOpt, objOpt, true, objOpt, objOpt, objOpt, objOpt, objOpt);//.Add(true);
xlBook.BeforeClose += xlBook_BeforeClose;
}
catch
{
xlApp = null;
if (!InitXl())
return succeed;
xlBook = xlApp.Workbooks.Open(templateFile, objOpt, true, objOpt, objOpt, objOpt, true, objOpt, objOpt, true, objOpt, objOpt, objOpt, objOpt, objOpt);//.Add(true);
}
Prc.Do("导出数据到Excel...");
// xlApp.Visible = true;
object oMissing = System.Reflection.Missing.Value;
#region Test Data
var xlSheet1 = (Worksheet)xlBook.Worksheets.get_Item(1);
var xlSheet2 = (Worksheet)xlBook.Worksheets.get_Item(2);
var dtPrg = ds.Tables["t_TestProgramResult"];
for (int prgRow = 0; prgRow < dtPrg.Rows.Count; prgRow++)
{
var dtItem = ds.Tables["T_TestItemResult"];
int itemCount = dtItem.Rows.Count;
// xlBook.CommandBars = new Microsoft.Office.Core.CommandBars();
// var oleObject = (OLEObject) xlSheet1.OLEObjects("CommandButton1");
// var cb=(Microsoft.Vbe.Interop.Forms.CommandButton)oleObject.Object;
// var obj = ((Microsoft.Office.Tools.Excel.Worksheet)xlSheet1).Controls.AddControl(new System.Windows.Forms.Button(), xlSheet1.get_Range(xlSheet1.Cells[1, "W"], xlSheet1.Cells[1, "Y"]), "ddddd");
xlSheet1.Cells[4, "H"] = dtPrg.Rows[0]["TestProgramName"].ToString();
xlSheet1.Cells[4, "W"] = dtPrg.Rows[0]["TestResult"].ToString();
try { xlSheet1.Cells[5, "H"] = Convert.ToInt32(dtPrg.Rows[0]["ElapsedTime"]) / 1000.0 + "s"; }
catch { }
xlSheet1.Cells[5, "W"] = dtPrg.Rows[0]["RunDate"].ToMyDateTimeString();
xlSheet1.Cells[6, "H"] = "5%";
xlSheet1.Cells[6, "W"] = dtPrg.Rows[0]["OperatorName"].ToString();
//列名加粗显示
//xlSheet.get_Range(xlSheet.Cells[rowIndex, 1], xlSheet.Cells[rowIndex, colCount]).Font.Bold = true;
//xlSheet.get_Range(xlSheet.Cells[rowIndex, 1], xlSheet.Cells[rowCount + 1, colCount]).Font.Name = "Arial";
//xlSheet.get_Range(xlSheet.Cells[rowIndex, 1], xlSheet.Cells[rowCount + 1, colCount]).Font.Size = "10";
int st1RowIdx = 8;
int st2RowIdx = 1;
int st2ColIdx = 1;
int[] waveIdxArr = new int[itemCount];
int[] waveLenArr = new int[itemCount];
for (int i = 0; i < itemCount; i++)
{
waveIdxArr[i] = st1RowIdx;
double rate = (double)i / itemCount;
Prc.Do("导出数据到Excel (" + rate.ToString("P0") + ")");
string itemName = dtItem.Rows[i]["TestItemName"].ToString();
var dtPrm = dtItem.Rows[i].GetChildRows("ProgramRel2").ToList();
var drPageArr = ds.Tables["t_prmpageset"].Select(string.Format("ItemName='{0}' and PageShow=1", itemName));
var drMeasArr = dtPrm.Where(p => p["PrmKind"].ToString().EqualsNoCase("meas")).ToList();
//var drWaveArr = dtPrm.Where(p => p["PrmName"].ToString().EqualsNoCase("fReadWave")).ToList();
string[] waveValueArr = new string[0];
foreach (var rowPrm in dtPrm)
{
if (rowPrm["PrmName"].ToString().EqualsNoCase("DSO_data"))
{
waveValueArr = rowPrm["PrmValue"].ToString().Split(",;".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
waveLenArr[i] = waveValueArr.Length;
}
}
var excRange = xlSheet1.get_Range(xlSheet1.Cells[st1RowIdx - 1, "C"], xlSheet1.Cells[st1RowIdx - 1, "Y"]);
excRange.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeBottom].LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
excRange.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeBottom].Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlMedium;
xlSheet1.Cells[st1RowIdx, "C"] = "UUT Test Sequence No." + (i + 1);// dt.Rows[i][""].ToString();
xlSheet1.Cells[st1RowIdx, "J"] = itemName;
xlSheet1.Cells[st1RowIdx, "V"] = dtItem.Rows[i]["ElapsedTime"].ToMyDateTimeString();
xlSheet1.Cells[st1RowIdx + 1, "A"] = i + 1;
excRange = xlSheet1.get_Range(xlSheet1.Cells[st1RowIdx + 0, "Z"], xlSheet1.Cells[st1RowIdx + 0, "Z"]);
// var btn = xlSheet1.Shapes.AddOLEObject("Forms.CommandButton.1", Type.Missing, false, false, Type.Missing, Type.Missing, Type.Missing, excRange.Left, excRange.Top, 60, 25);
// btn.Name = "cmdBtn_" + i;
// var cbtn = (Microsoft.Vbe.Interop.Forms.CommandButton)((OLEObject)btn.OLEFormat.Object).Object;
// cbtn.Caption = "显示图形" /*+ (i + 1)*/;
// cbtn.Font.Name = "宋体";
// cbtn.BackColor = System.Drawing.Color.RoyalBlue.ToInt();
// // var oModule = xlBook.VBProject.VBComponents.Add(Microsoft.Vbe.Interop.vbext_ComponentType.vbext_ct_StdModule);
// var oModule = xlBook.VBProject.VBComponents.Item("Sheet1");
// string sCode = "Sub cmdBtn_" + i + "_Click()\r\n"
// + " If cmdBtn_" + i + ".Caption= \"显示图形\" Then\r\n"
// + " cmdBtn_" + i + ".Caption= \"关闭图形\"\r\n"
// + string.Format(" Call copychart({0},{1},1)\r\n", i + 1, st1RowIdx + 1)
// + " Else \r\n"
// + " cmdBtn_" + i + ".Caption= \"显示图形\"\r\n"
// + string.Format(" Call copychart({0},{1},0)\r\n", i + 1, st1RowIdx + 1)
// + " End If\r\n"
// + "End sub";
// oModule.CodeModule.AddFromString(sCode);
// var oleObject = (Microsoft.Vbe.Interop.Forms.CommandButton)((OLEObject)xlSheet1.OLEObjects("CommandButton1")).Object;
#region Set Param
for (int j = 0; j < drPageArr.Length; j++)
{
string TextPrmValue = "";
string prmName = drPageArr[j]["ItemPrm"].ToString();
var drPrm = dtPrm.Find(p => p["PrmName"].ToString().EqualsNoCase(prmName));
if (drPrm == null)
continue;
// dvPrm.RowFilter = string.Format("ItemPrm='{0}'", prmName);
string prmValue = drPrm["prmValue"].ToString();
string sFormat = drPageArr[j]["PageFormat"].ToString();
string TextPrmName = drPageArr[j]["PageText"].ToString();
string iTmp = "0";
if (TextPrmName.IsEmpty())
TextPrmName = prmName;
if (!prmValue.IsEmpty())
{
if (!sFormat.IsEmpty())
{
try
{
if (!sFormat.StartsWith("{") && !sFormat.EndsWith("}"))
sFormat = "{" + sFormat + "}";
if (prmValue.Contains(";"))
{
String[] ss = prmValue.Split(';');
prmValue = "";
for (int k = 0; k < ss.Length; k++)
{
if (string.IsNullOrWhiteSpace(ss[k]))
continue;
double d = Convert.ToDouble(ss[k].Trim());
prmValue += string.Format(sFormat, d) + ";";
}
prmValue.TrimEnd(';');
}
else
{
double d = Convert.ToDouble(drPrm["prmValue"]);
prmValue = string.Format(sFormat, d);
}
}
catch { }
}
else
{
if (prmName.EqualsNoCase("iconstmode"))
{
iTmp = drPrm["prmValue"].ToString();
}
}
if (drPrm["prmName"].ToString().ToLower().EndsWith("array"))
{
if (string.IsNullOrWhiteSpace(TextPrmValue))
TextPrmValue = "= " + prmValue;
else
TextPrmValue += "," + prmValue;
}
else TextPrmValue = "= " + prmValue;
}
else if (!sFormat.IsEmpty())
TextPrmValue = sFormat;
if (prmName.EqualsNoCase("iconstmode"))
{
switch (iTmp)
{
case "":
TextPrmValue = "= " + "CC";
break;
case "0":
TextPrmValue = "= " + "CC";
break;
case "1":
TextPrmValue = "= " + "CV";
break;
case "2":
TextPrmValue = "= " + "CR";
break;
case "3":
TextPrmValue = "= " + "LED";
break;
default:
TextPrmValue = "= CC";
break;
}
}
if (!TextPrmValue.StartsWith(TextPrmName))
TextPrmValue = TextPrmName + " " + TextPrmValue;
if (j % 2 == 0)
xlSheet1.Cells[st1RowIdx + j / 2, "C"] = TextPrmValue;
else
xlSheet1.Cells[st1RowIdx + j / 2 + 1, "O"] = TextPrmValue;
if (j % 10 == 1)
Prc.Do("导出数据到Excel (" + (rate + 0.5 / (drPageArr.Length + drMeasArr.Count + waveValueArr.Length)).ToString("P0") + ")");
}
#endregion
// Prc.Do(rate+0.5/rowCount );
int rowMeas = st1RowIdx + 1 + (int)drPageArr.Length / 2;// (int)Math.Ceiling((double)drPageArr.Length / 2);
xlSheet1.Cells[rowMeas, "C"] = "Test Name";
xlSheet1.Cells[rowMeas, "I"] = "Max Value";
xlSheet1.Cells[rowMeas, "M"] = "Test Value";
xlSheet1.Cells[rowMeas, "R"] = "Min Value";
xlSheet1.Cells[rowMeas, "W"] = "Test Result";
xlSheet1.get_Range(xlSheet1.Cells[rowMeas, 3], xlSheet1.Cells[rowMeas, 26]).Font.Bold = true;
for (int j = 0; j < drMeasArr.Count; j++)
{
string sUnit = drMeasArr[j]["PrmValueUnit"].ToString();
sUnit = sUnit.IsEmpty() ? "" : "(" + sUnit + ")";
xlSheet1.Cells[rowMeas + j + 1, "C"] = drMeasArr[j]["PrmInfo"] + sUnit;
xlSheet1.Cells[rowMeas + j + 1, "I"] = drMeasArr[j]["PrmMaxValue"];
xlSheet1.Cells[rowMeas + j + 1, "M"] = drMeasArr[j]["PrmValue"];
xlSheet1.Cells[rowMeas + j + 1, "R"] = drMeasArr[j]["PrmMinValue"];
xlSheet1.Cells[rowMeas + j + 1, "X"] = drMeasArr[j]["PssValue"];
if (j % 10 == 1)
Prc.Do("导出数据到Excel (" + (rate + (1.0 / itemCount) * (double)(drPageArr.Length + j) / (drPageArr.Length + drMeasArr.Count + waveValueArr.Length)).ToString("P0") + ")");
}
// st1RowIdx = rowMeas + drMeasArr.Count + 1;
st1RowIdx += Math.Max(10, drPageArr.Length / 2 + drMeasArr.Count + 2);
// xlSheet2.Cells[st2RowIdx, st2ColIdx] = "NO." + (i + 1);
// excRange = xlSheet2.get_Range(xlSheet2.Cells[1, st2ColIdx - 1], xlSheet2.Cells[Math.Max(10, waveValueArr.Length + 1), st2ColIdx - 1]);
// excRange.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeRight].LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
// excRange.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeRight].Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin;
// for (int j = 0; j < waveValueArr.Length; j++)
// {
// xlSheet2.Cells[st2RowIdx + j + 1, st2ColIdx ] =double.Parse( waveValueArr[j]);
// if (j % 10 == 1)
// Prc.Do(rate + (1.0 / rowCount) * (double)(drPageArr.Length + drMeasArr.Count + j) / (drPageArr.Length + drMeasArr.Count + waveValueArr.Length));
// }
int wj = 0;
Parallel.For(0, waveValueArr.Length, (j) =>
{
xlSheet2.Cells[st2RowIdx + j, st2ColIdx] = waveValueArr[j];
System.Threading.Interlocked.Increment(ref wj);
if (wj % 10 == 1)
Prc.Do("导出数据到Excel (" + (rate + (1.0 / itemCount) * (double)(drPageArr.Length + drMeasArr.Count + wj) / (drPageArr.Length + drMeasArr.Count + waveValueArr.Length)).ToString("P0") + ")");
});
st2ColIdx++;
}
int wi = 0;
// Parallel.For(0, itemCount, (i) =>//
for (int i = 0; i < itemCount; i++)
{
var chart = ((ChartObject)xlSheet2.ChartObjects(1)).Chart;
// chart.ChartArea.Select();
// chart.Paste(xlSheet1.Cells[st1RowIdx + 1, "Z"]);
// var chartGroup = (ChartGroup)chart.ChartGroups(1);
// var series = (Series)chartGroup.SeriesCollection(1);
// series.Values = st1RowIdx;
chart.ChartWizard(xlSheet2.get_Range(xlSheet2.Cells[1, st2ColIdx], xlSheet2.Cells[waveLenArr[i], st2ColIdx]), XlChartType.xlLine, Type.Missing, XlRowCol.xlColumns, 1, 1, true, "", "", "", "rrr");
//chart.SetSourceData(xlSheet2.get_Range(xlSheet2.Cells[4, 5 + (0) * 4], xlSheet2.Cells[112, 7 + (0) * 4]));
chart.ChartArea.Copy();//.Copy(Type.Missing,xlSheet1);
xlSheet1.Paste(xlSheet1.Cells[waveIdxArr[i], "Z"]);
// chart.SetSourceData(xlSheet2.get_Range(xlSheet2.Cells[1, st2ColIdx ], xlSheet2.Cells[waveValueArr.Length, st2ColIdx]));
System.Threading.Interlocked.Increment(ref wi);
Prc.Do("生成Excel图表 (" + ((double)wi / itemCount).ToString("P0") + ")");
// });
// xlSheet.Cells.EntireColumn.AutoFit();
xlSheet1.get_Range(xlSheet1.Cells[8, 3], xlSheet1.Cells[st1RowIdx, 26]).Font.Name = "Arial";
}
}
#endregion
xlApp.DisplayAlerts = false;
path = Path.GetFullPath(path);
xlBook.SaveCopyAs(path);
xlApp.Visible = true;
// xlBook.Close(false, null, null);
// xlApp.Workbooks.Close();
// xlApp.Visible = false;
// Marshal.ReleaseComObject(xlSheet1);
// Marshal.ReleaseComObject(xlBook);
Prc.Do("成功导出到Excel");
// xlBook = null;
succeed = true;
}
catch (Exception ex)
{
release();
throw ex;
}
finally
{
IntPtr t = new IntPtr(xlApp.Hwnd);
int k = 0;
GetWindowThreadProcessId(t, out k);
System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k);
// p.Kill();
//release();
}
return succeed;
}
}
static void xlBook_BeforeClose(ref bool Cancel)
{
release();
}
public static bool ExportExcel0(System.Data.DataSet ds, string path, string templateFile, Action Prc = null)
{
lock (exportLock)
{
bool succeed = false;
if (ds == null && ds.Tables.Count == 0)
return false;
Prc.Do(-1);
if (!InitXl())
return false;
// xlApp.Visible = true;
try
{
object objOpt = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Workbook xlBook = null;
try
{
xlBook = xlApp.Workbooks.Open(templateFile, objOpt, true, objOpt, objOpt, objOpt, true, objOpt, objOpt, true, objOpt, objOpt, objOpt, objOpt, objOpt);//.Add(true);
}
catch
{
xlApp = null;
if (!InitXl())
return false;
xlBook = xlApp.Workbooks.Open(templateFile, objOpt, true, objOpt, objOpt, objOpt, true, objOpt, objOpt, true, objOpt, objOpt, objOpt, objOpt, objOpt);//.Add(true);
}
Prc.Do(-2);
object oMissing = System.Reflection.Missing.Value;
#region Test Data
var xlSheet1 = (Worksheet)xlBook.Worksheets.get_Item(1);
var xlSheet2 = (Worksheet)xlBook.Worksheets.get_Item(2);
var dtPrg = ds.Tables["t_TestProgramResult"];
var dtItem = ds.Tables["T_TestItemResult"];
int rowCount = dtItem.Rows.Count;
// xlBook.CommandBars = new Microsoft.Office.Core.CommandBars();
// var oleObject = (OLEObject) xlSheet1.OLEObjects("CommandButton1");
// var cb=(Microsoft.Vbe.Interop.Forms.CommandButton)oleObject.Object;
// var obj = ((Microsoft.Office.Tools.Excel.Worksheet)xlSheet1).Controls.AddControl(new System.Windows.Forms.Button(), xlSheet1.get_Range(xlSheet1.Cells[1, "W"], xlSheet1.Cells[1, "Y"]), "ddddd");
xlSheet1.Cells[4, "H"] = dtPrg.Rows[0]["TestProgramName"].ToString();
xlSheet1.Cells[4, "W"] = dtPrg.Rows[0]["TestResult"].ToString();
try { xlSheet1.Cells[5, "H"] = Convert.ToInt32(dtPrg.Rows[0]["ElapsedTime"]) / 1000.0 + "s"; }
catch { }
xlSheet1.Cells[5, "W"] = dtPrg.Rows[0]["RunDate"].ToMyDateTimeString();
xlSheet1.Cells[6, "H"] = "5%";
xlSheet1.Cells[6, "W"] = dtPrg.Rows[0]["OperatorName"].ToString();
//列名加粗显示
//xlSheet.get_Range(xlSheet.Cells[rowIndex, 1], xlSheet.Cells[rowIndex, colCount]).Font.Bold = true;
//xlSheet.get_Range(xlSheet.Cells[rowIndex, 1], xlSheet.Cells[rowCount + 1, colCount]).Font.Name = "Arial";
//xlSheet.get_Range(xlSheet.Cells[rowIndex, 1], xlSheet.Cells[rowCount + 1, colCount]).Font.Size = "10";
bool b = false;
int st1RowIdx = 8;
int st2RowIdx = 4;
int st2ColIdx = 5;
for (int i = 0; i < rowCount; i++)
{
double rate = (double)i / rowCount;
Prc.Do(rate);
string itemName = dtItem.Rows[i]["TestItemName"].ToString();
var dtPrm = dtItem.Rows[i].GetChildRows("ProgramRel2").ToList();
var drPageArr = ds.Tables["t_prmpageset"].Select(string.Format("ItemName='{0}' and PageShow=1", itemName));
var drMeasArr = dtPrm.Where(p => p["PrmKind"].ToString().EqualsNoCase("meas")).ToList();
var drWaveArr = dtPrm.Where(p => p["PrmName"].ToString().EqualsNoCase("fReadWave")).ToList();
string[] waveValueArr = new string[0];
if (drWaveArr.Count > 0)
waveValueArr = drWaveArr[0]["PrmValue"].ToString().Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
var excRange = xlSheet1.get_Range(xlSheet1.Cells[st1RowIdx - 1, "C"], xlSheet1.Cells[st1RowIdx - 1, "Y"]);
excRange.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeBottom].LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
excRange.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeBottom].Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlMedium;
xlSheet1.Cells[st1RowIdx, "C"] = "UUT Test Sequence No." + (i + 1);// dt.Rows[i][""].ToString();
xlSheet1.Cells[st1RowIdx, "J"] = itemName;
xlSheet1.Cells[st1RowIdx, "V"] = dtItem.Rows[i]["ElapsedTime"].ToMyDateTimeString();
xlSheet1.Cells[st1RowIdx + 1, "A"] = i + 1;
excRange = xlSheet1.get_Range(xlSheet1.Cells[st1RowIdx + 1, "Z"], xlSheet1.Cells[st1RowIdx + 1, "Z"]);
var btn = xlSheet1.Shapes.AddOLEObject("Forms.CommandButton.1", Type.Missing, false, false, Type.Missing, Type.Missing, Type.Missing, excRange.Left, excRange.Top, 60, 25);
btn.Name = "cmdBtn_" + i;
var cbtn = (Microsoft.Vbe.Interop.Forms.CommandButton)((OLEObject)btn.OLEFormat.Object).Object;
// var cbtn = (Microsoft.Vbe.Interop.Forms.CommandButton)((OLEObject)xlSheet1.OLEObjects("cmdBtn_" + i)).Object;
cbtn.Caption = "显示图形" /*+ (i + 1)*/;
cbtn.Font.Name = "宋体";
cbtn.BackColor = System.Drawing.Color.RoyalBlue.ToInt();
// cbtn.Click += () =>
// {
// if (cbtn.Caption == "显示图形")
// {
// cbtn.Caption = "关闭图形";
// RunMacro(xlApp, new object[] { "copychartA", (i + 1), 12, 1 });
// }
// else{
// cbtn.Caption = "显示图形";
// RunMacro(xlApp, new object[] { "copychartA", (i + 1), 12, 0 });
// }
// };
// var oModule = xlBook.VBProject.VBComponents.Add(Microsoft.Vbe.Interop.vbext_ComponentType.vbext_ct_StdModule);
var oModule = xlBook.VBProject.VBComponents.Item("Sheet1");
string sCode = "Sub cmdBtn_" + i + "_Click()\r\n"
+ " If cmdBtn_" + i + ".Caption= \"显示图形\" Then\r\n"
+ " cmdBtn_" + i + ".Caption= \"关闭图形\"\r\n"
+ string.Format(" Call copychart({0},{1},1)\r\n", i + 1, st1RowIdx + 1)
+ " Else \r\n"
+ " cmdBtn_" + i + ".Caption= \"显示图形\"\r\n"
+ string.Format(" Call copychart({0},{1},0)\r\n", i + 1, st1RowIdx + 1)
+ " End If\r\n"
+ "End sub";
oModule.CodeModule.AddFromString(sCode);
// var oleObject = (Microsoft.Vbe.Interop.Forms.CommandButton)((OLEObject)xlSheet1.OLEObjects("CommandButton1")).Object;
#region Set Param
for (int j = 0; j < drPageArr.Length; j++)
{
string TextPrmValue = "";
string prmName = drPageArr[j]["ItemPrm"].ToString();
var drPrm = dtPrm.Find(p => p["PrmName"].ToString().EqualsNoCase(prmName));
if (drPrm == null)
continue;
// dvPrm.RowFilter = string.Format("ItemPrm='{0}'", prmName);
string prmValue = drPrm["prmValue"].ToString();
string sFormat = drPageArr[j]["PageFormat"].ToString();
string TextPrmName = drPageArr[j]["PageText"].ToString();
string iTmp = "0";
if (TextPrmName.IsEmpty())
TextPrmName = prmName;
if (!prmValue.IsEmpty())
{
if (!sFormat.IsEmpty())
{
try
{
if (!sFormat.StartsWith("{") && !sFormat.EndsWith("}"))
sFormat = "{" + sFormat + "}";
if (prmValue.Contains(";"))
{
String[] ss = prmValue.Split(';');
prmValue = "";
for (int k = 0; k < ss.Length; k++)
{
if (string.IsNullOrWhiteSpace(ss[k]))
continue;
double d = Convert.ToDouble(ss[k].Trim());
prmValue += string.Format(sFormat, d) + ";";
}
prmValue.TrimEnd(';');
}
else
{
double d = Convert.ToDouble(drPrm["prmValue"]);
prmValue = string.Format(sFormat, d);
}
}
catch { }
}
else
{
if (prmName.EqualsNoCase("iconstmode"))
{
iTmp = drPrm["prmValue"].ToString();
}
}
if (drPrm["prmName"].ToString().ToLower().EndsWith("array"))
{
if (string.IsNullOrWhiteSpace(TextPrmValue))
TextPrmValue = "= " + prmValue;
else
TextPrmValue += "," + prmValue;
}
else TextPrmValue = "= " + prmValue;
}
else if (!sFormat.IsEmpty())
TextPrmValue = sFormat;
if (prmName.EqualsNoCase("iconstmode"))
{
switch (iTmp)
{
case "":
TextPrmValue = "= " + "CC";
break;
case "0":
TextPrmValue = "= " + "CC";
break;
case "1":
TextPrmValue = "= " + "CV";
break;
case "2":
TextPrmValue = "= " + "CR";
break;
case "3":
TextPrmValue = "= " + "LED";
break;
default:
TextPrmValue = "= CC";
break;
}
}
if (!TextPrmValue.StartsWith(TextPrmName))
TextPrmValue = TextPrmName + " " + TextPrmValue;
if (j % 2 == 0)
xlSheet1.Cells[st1RowIdx + j / 2, "C"] = TextPrmValue;
else
xlSheet1.Cells[st1RowIdx + j / 2 + 1, "O"] = TextPrmValue;
if (j % 10 == 1)
Prc.Do(rate + 0.5 / (drPageArr.Length + drMeasArr.Count + waveValueArr.Length));
}
#endregion
// Prc.Do(rate+0.5/rowCount );
int rowMeas = st1RowIdx + 1 + (int)drPageArr.Length / 2;// (int)Math.Ceiling((double)drPageArr.Length / 2);
xlSheet1.Cells[rowMeas, "C"] = "Test Name";
xlSheet1.Cells[rowMeas, "I"] = "Max Value";
xlSheet1.Cells[rowMeas, "M"] = "Test Value";
xlSheet1.Cells[rowMeas, "R"] = "Min Value";
xlSheet1.Cells[rowMeas, "W"] = "Test Result";
xlSheet1.get_Range(xlSheet1.Cells[rowMeas, 3], xlSheet1.Cells[rowMeas, 26]).Font.Bold = true;
for (int j = 0; j < drMeasArr.Count; j++)
{
string sUnit = drMeasArr[j]["PrmValueUnit"].ToString();
sUnit = sUnit.IsEmpty() ? "" : "(" + sUnit + ")";
xlSheet1.Cells[rowMeas + j + 1, "C"] = drMeasArr[j]["PrmInfo"] + sUnit;
xlSheet1.Cells[rowMeas + j + 1, "I"] = drMeasArr[j]["PrmMaxValue"];
xlSheet1.Cells[rowMeas + j + 1, "M"] = drMeasArr[j]["PrmValue"];
xlSheet1.Cells[rowMeas + j + 1, "R"] = drMeasArr[j]["PrmMinValue"];
xlSheet1.Cells[rowMeas + j + 1, "X"] = drMeasArr[j]["PssValue"];
if (j % 50 == 1)
Prc.Do(rate + (1.0 / rowCount) * (double)(drPageArr.Length + j) / (drPageArr.Length + drMeasArr.Count + waveValueArr.Length));
}
st1RowIdx = rowMeas + drMeasArr.Count + 1;
xlSheet2.Cells[st2RowIdx, st2ColIdx] = "NO." + (i + 1);
excRange = xlSheet2.get_Range(xlSheet2.Cells[1, st2ColIdx - 1], xlSheet2.Cells[Math.Max(10, waveValueArr.Length + 1), st2ColIdx - 1]);
excRange.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeRight].LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
excRange.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeRight].Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin;
for (int j = 0; j < waveValueArr.Length; j++)
{
xlSheet2.Cells[st2RowIdx + j + 1, st2ColIdx + i + 2] = waveValueArr[j];
if (j % 20 == 1)
Prc.Do(rate + (1.0 / rowCount) * (double)(drPageArr.Length + drMeasArr.Count + j) / (drPageArr.Length + drMeasArr.Count + waveValueArr.Length));
}
st2ColIdx += 4;
}
// xlSheet.Cells.EntireColumn.AutoFit();
xlSheet1.get_Range(xlSheet1.Cells[8, 3], xlSheet1.Cells[st1RowIdx, 26]).Font.Name = "Arial";
#endregion
xlApp.DisplayAlerts = false;
path = Path.GetFullPath(path);
xlBook.SaveCopyAs(path);
xlApp.Visible = true;
// xlBook.Close(false, null, null);
// xlApp.Workbooks.Close();
// xlApp.Visible = false;
// Marshal.ReleaseComObject(xlSheet1);
// Marshal.ReleaseComObject(xlBook);
Prc.Do(1);
// xlBook = null;
succeed = true;
}
catch (Exception ex)
{
release();
throw ex;
}
finally
{
release();
}
return succeed;
}
}
///
/// 执行宏
///
/// Excel对象
/// 参数(第一个参数为指定宏名称,后面为指定宏的参数值)
/// 宏返回值
private static object RunMacro(object oApp, object[] oRunArgs)
{
try
{
object objRtn = oApp.GetType().InvokeMember("Run", System.Reflection.BindingFlags.Default | System.Reflection.BindingFlags.InvokeMethod, null, oApp, oRunArgs);
return objRtn;
}
catch (Exception ex)
{
release();
if (ex.InnerException.Message.ToString().Length > 0)
{
throw ex.InnerException;
}
else
{
throw ex;
}
}
}
static void release()
{
try
{
IntPtr t = new IntPtr(xlApp.Hwnd);
int k = 0;
GetWindowThreadProcessId(t, out k);
System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k);
p.Kill();
xlApp.Workbooks.Close();
xlApp.Quit();
Marshal.ReleaseComObject(xlApp);
int generation = System.GC.GetGeneration(xlApp);
xlApp = null;
System.GC.Collect(generation);
}
catch { xlApp = null; }
}
}