110,533
社区成员
发帖
与我相关
我的任务
分享
// 使打开文件对话框(openfiledialog)只显示Excel文件
this.openFileDialog1.FileName = "*.xls";
if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
{
// *********** 这里调用Open方法打开Excel工作簿 ****************
// 多数使用缺省值 (除了 read-only我们设置它为 true)
Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open(openFileDialog1.FileName, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, null, null);
// 取得工作簿(workbook)中表单的集合(sheets)
Excel.Sheets sheets = theWorkbook.Worksheets;
// 取得表单集合中唯一的一个表(worksheet)
Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);
// 读取前10行,置入listview
for (int i = 1; i <= 10; i++)
{
Excel.Range range = worksheet.get_Range("A" + i.ToString(), "J" + i.ToString());
System.Array myvalues = (System.Array)range.Cells.Value2;
string[] strArray = ConvertToStringArray(myvalues);
if (i != 1)
{
string[] items = strArray[0].Split(' ');
ListViewItem item = new ListViewItem();
item.ImageIndex = 0;
item.Text = items[0];
for (int b = 1; b < items.Length; b++)
{
if (items[b] != "")
{
item.SubItems.Add(items[b]);
}
}
listView1.Items.Add(item);
}
else
{
string[] columns = strArray[0].Split(' ');
foreach (string var in columns)
{
if (var != "")
{
listView1.Columns.Add(var, 70);
}
}
}
}
}
}
public string[] ConvertToStringArray(System.Array values)
{
// 生成新的字符串数组
string[] theArray = new string[values.Length];
// 把二维的数组转化为一维的字符串数组loop through the 2-D System.Array and populate the 1-D String Array
for (int i = 1; i <= values.Length; i++)
{
if (values.GetValue(1, i) == null)
theArray[i - 1] = "";
else
theArray[i - 1] = (string)values.GetValue(1, i).ToString();
}
return theArray;
}
private Excel.Application eApp;
void axWebBrowser1_NavigateComplete2(object sender, DWebBrowserEvents2_NavigateComplete2Event e)
{
Object o = e.pDisp;
Object oDocument = o.GetType().InvokeMember("Document", BindingFlags.GetProperty, null, o, null);
Object oApplication = o.GetType().InvokeMember("Application", BindingFlags.GetProperty, null, oDocument, null);
eApp = (Excel.Application)oApplication;
}