Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用Excel OleDb按图纸顺序获取图纸名称_C#_Excel_Oledb_Server Side - Fatal编程技术网

C# 使用Excel OleDb按图纸顺序获取图纸名称

C# 使用Excel OleDb按图纸顺序获取图纸名称,c#,excel,oledb,server-side,C#,Excel,Oledb,Server Side,我正在使用OleDb阅读包含许多工作表的excel工作簿 我需要阅读表格名称,但我需要按照电子表格中定义的顺序阅读;所以如果我有一个像这样的文件 |_____|_____|____|____|____|____|____|____|____| |_____|_____|____|____|____|____|____|____|____| |_____|_____|____|____|____|____|____|____|____| \__GERMANY__/\__UK__/\__IRELAN

我正在使用OleDb阅读包含许多工作表的excel工作簿

我需要阅读表格名称,但我需要按照电子表格中定义的顺序阅读;所以如果我有一个像这样的文件

|_____|_____|____|____|____|____|____|____|____|
|_____|_____|____|____|____|____|____|____|____|
|_____|_____|____|____|____|____|____|____|____|
\__GERMANY__/\__UK__/\__IRELAND__/
那我得去拿字典

1="GERMANY", 
2="UK", 
3="IRELAND"
我尝试过使用
OleDbConnection.GetOleDbSchemaTable()
,这会给出名称列表,但它会按字母顺序排序。alpha排序意味着我不知道特定名称对应的页码。所以我得到了

GERMANY, IRELAND, UK
它改变了英国和爱尔兰的顺序

我需要对其进行排序的原因是,我必须让用户按名称或索引选择一系列数据;他们可以要求“从德国到爱尔兰的所有数据”或“从表1到表3的数据”

任何想法都将不胜感激


如果我可以使用office互操作类,这将非常简单。不幸的是,我不能这样做,因为interop类在非交互环境(如windows服务和ASP.NET站点)中不能可靠地工作,所以我需要使用OLEDB。

你能不能从0循环到名称计数-1?这样你就可以把它们按正确的顺序排列

编辑

我从评论中注意到,对于使用互操作类来检索工作表名称,存在很多问题。因此,下面是一个使用OLEDB检索它们的示例:

/// <summary>
/// This method retrieves the excel sheet names from 
/// an excel workbook.
/// </summary>
/// <param name="excelFile">The excel file.</param>
/// <returns>String[]</returns>
private String[] GetExcelSheetNames(string excelFile)
{
    OleDbConnection objConn = null;
    System.Data.DataTable dt = null;

    try
    {
        // Connection String. Change the excel file to the file you
        // will search.
        String connString = "Provider=Microsoft.Jet.OLEDB.4.0;" + 
          "Data Source=" + excelFile + ";Extended Properties=Excel 8.0;";
        // Create connection object by using the preceding connection string.
        objConn = new OleDbConnection(connString);
        // Open connection with the database.
        objConn.Open();
        // Get the data table containg the schema guid.
        dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

        if(dt == null)
        {
           return null;
        }

        String[] excelSheets = new String[dt.Rows.Count];
        int i = 0;

        // Add the sheet name to the string array.
        foreach(DataRow row in dt.Rows)
        {
           excelSheets[i] = row["TABLE_NAME"].ToString();
           i++;
        }

        // Loop through all of the sheets if you want too...
        for(int j=0; j < excelSheets.Length; j++)
        {
            // Query each excel sheet.
        }

        return excelSheets;
   }
   catch(Exception ex)
   {
       return null;
   }
   finally
   {
      // Clean up.
      if(objConn != null)
      {
          objConn.Close();
          objConn.Dispose();
      }
      if(dt != null)
      {
          dt.Dispose();
      }
   }
}
//
///此方法从中检索excel工作表名称
///excel工作簿。
/// 
///excel文件。
///字符串[]
私有字符串[]GetExcelSheetNames(字符串excelFile)
{
OleDbConnection objConn=null;
System.Data.DataTable dt=null;
尝试
{
//连接字符串。将excel文件更改为您需要的文件
//将搜索。
String connString=“Provider=Microsoft.Jet.OLEDB.4.0;”+
“数据源=“+excelFile+”;扩展属性=Excel 8.0;”;
//使用前面的连接字符串创建连接对象。
objConn=新的OLEDB连接(connString);
//打开与数据库的连接。
objConn.Open();
//获取包含架构guid的数据表。
dt=objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,null);
如果(dt==null)
{
返回null;
}
String[]excelSheets=新字符串[dt.Rows.Count];
int i=0;
//将工作表名称添加到字符串数组中。
foreach(数据行中的数据行)
{
excelSheets[i]=行[“表名称”]。ToString();
i++;
}
//如果你想的话,也可以在所有的表格中循环。。。
对于(int j=0;j

从CodeProject中提取。

这对我很有用。从这里偷来的:


试试这个。以下是按顺序获取图纸名称的代码

private Dictionary<int, string> GetExcelSheetNames(string fileName)
{
    Excel.Application _excel = null;
    Excel.Workbook _workBook = null;
    Dictionary<int, string> excelSheets = new Dictionary<int, string>();
    try
    {
        object missing = Type.Missing;
        object readOnly = true;
        Excel.XlFileFormat.xlWorkbookNormal
        _excel = new Excel.ApplicationClass();
        _excel.Visible = false;
        _workBook = _excel.Workbooks.Open(fileName, 0, readOnly, 5, missing,
            missing, true, Excel.XlPlatform.xlWindows, "\\t", false, false, 0, true, true, missing);
        if (_workBook != null)
        {
            int index = 0;
            foreach (Excel.Worksheet sheet in _workBook.Sheets)
            {
                // Can get sheet names in order they are in workbook
                excelSheets.Add(++index, sheet.Name);
            }
        }
    }
    catch (Exception e)
    {
        return null;
    }
    finally
    {
        if (_excel != null)
        {

            if (_workBook != null)
                _workBook.Close(false, Type.Missing, Type.Missing);
            _excel.Application.Quit();
        }
        _excel = null;
        _workBook = null;
    }
    return excelSheets;
}
专用字典GetExcelSheetNames(字符串文件名)
{
Excel.Application\u Excel=null;
Excel.Workbook\u Workbook=null;
字典excelSheets=新字典();
尝试
{
对象缺失=类型。缺失;
对象只读=真;
Excel.XlFileFormat.xlWorkbookNormal
_excel=新的excel.ApplicationClass();
_excel.Visible=false;
_工作簿=\u excel.Workbooks.Open(文件名,0,只读,5,缺失,
缺失,true,Excel.XlPlatform.xlWindows,“\\t”,false,false,0,true,true,缺失);
如果(_工作簿!=null)
{
int指数=0;
foreach(工作簿中的Excel.Workbench工作表)
{
//可以按工作表在工作簿中的顺序获取工作表名称
excelSheets.Add(++索引,sheet.Name);
}
}
}
捕获(例外e)
{
返回null;
}
最后
{
如果(_excel!=null)
{
如果(_工作簿!=null)
_工作簿.Close(false,Type.Missing,Type.Missing);
_excel.Application.Quit();
}
_excel=null;
_工作簿=空;
}
返回表格;
}

由于上述代码不包括提取Excel 2007工作表名称列表的步骤,以下代码也适用于Excel(97-2003)和Excel 2007:

public List<string> ListSheetInExcel(string filePath)
{
   OleDbConnectionStringBuilder sbConnection = new OleDbConnectionStringBuilder();
   String strExtendedProperties = String.Empty;
   sbConnection.DataSource = filePath;
   if (Path.GetExtension(filePath).Equals(".xls"))//for 97-03 Excel file
   {
      sbConnection.Provider = "Microsoft.Jet.OLEDB.4.0";
      strExtendedProperties = "Excel 8.0;HDR=Yes;IMEX=1";//HDR=ColumnHeader,IMEX=InterMixed
   }
   else if (Path.GetExtension(filePath).Equals(".xlsx"))  //for 2007 Excel file
   {
      sbConnection.Provider = "Microsoft.ACE.OLEDB.12.0";
      strExtendedProperties = "Excel 12.0;HDR=Yes;IMEX=1";
   }
   sbConnection.Add("Extended Properties",strExtendedProperties);
   List<string> listSheet = new List<string>();
   using (OleDbConnection conn = new OleDbConnection(sbConnection.ToString()))
   {
     conn.Open();
     DataTable dtSheet = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);         
     foreach (DataRow drSheet in dtSheet.Rows)
     {
        if (drSheet["TABLE_NAME"].ToString().Contains("$"))//checks whether row contains '_xlnm#_FilterDatabase' or sheet name(i.e. sheet name always ends with $ sign)
        {
             listSheet.Add(drSheet["TABLE_NAME"].ToString());
        } 
     }
  }
 return listSheet;
}
公共列表ListSheetInXcel(字符串文件路径)
{
OleDbConnectionStringBuilder sbConnection=新的OleDbConnectionStringBuilder();
String strExtendedProperties=String.Empty;
sbConnection.DataSource=文件路径;
97-03 Excel文件的if(Path.GetExtension(filePath).Equals(“.xls”)//
{
sbConnection.Provider=“Microsoft.Jet.OLEDB.4.0”;
strExtendedProperties=“Excel 8.0;HDR=Yes;IMEX=1”;//HDR=ColumnHeader,IMEX=mixed
}
else if(Path.GetExtension(filePath).Equals(“.xlsx”)//用于2007 Excel文件
{
sbConnection.Provider=“Microsoft.ACE.OLEDB.12.0”;
strExtendedProperties=“Excel 12.0;HDR=Yes;IMEX=1”;
}
添加(“扩展属性”,strExtendedProperties);
List listSheet=新列表();
使用(OleDbConnection conn=新的OleDbConnection(sbConnection.ToString()))
{
conn.Open();
DataTable dtSheet=conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,null);
foreach(dtSheet.Rows中的数据行drSheet)
{
if(drSheet[“TABLE_NAME”].ToString().Contains(“$”)//检查行是否包含“_xlnm 35; _FilterDatabase”或工作表名称(即工作表名称始终以$sign结尾)
{
添加(drSheet[“TABLE_NAME”].ToString());
} 
}
}
返回列表;
}
上述函数返回工作表的详细列表
public List<string> ListSheetInExcel(string filePath)
{
   OleDbConnectionStringBuilder sbConnection = new OleDbConnectionStringBuilder();
   String strExtendedProperties = String.Empty;
   sbConnection.DataSource = filePath;
   if (Path.GetExtension(filePath).Equals(".xls"))//for 97-03 Excel file
   {
      sbConnection.Provider = "Microsoft.Jet.OLEDB.4.0";
      strExtendedProperties = "Excel 8.0;HDR=Yes;IMEX=1";//HDR=ColumnHeader,IMEX=InterMixed
   }
   else if (Path.GetExtension(filePath).Equals(".xlsx"))  //for 2007 Excel file
   {
      sbConnection.Provider = "Microsoft.ACE.OLEDB.12.0";
      strExtendedProperties = "Excel 12.0;HDR=Yes;IMEX=1";
   }
   sbConnection.Add("Extended Properties",strExtendedProperties);
   List<string> listSheet = new List<string>();
   using (OleDbConnection conn = new OleDbConnection(sbConnection.ToString()))
   {
     conn.Open();
     DataTable dtSheet = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);         
     foreach (DataRow drSheet in dtSheet.Rows)
     {
        if (drSheet["TABLE_NAME"].ToString().Contains("$"))//checks whether row contains '_xlnm#_FilterDatabase' or sheet name(i.e. sheet name always ends with $ sign)
        {
             listSheet.Add(drSheet["TABLE_NAME"].ToString());
        } 
     }
  }
 return listSheet;
}
using Microsoft.Office.Interop.Excel;

string filename = "C:\\romil.xlsx";

object missing = System.Reflection.Missing.Value;

Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();

Microsoft.Office.Interop.Excel.Workbook wb =excel.Workbooks.Open(filename,  missing,  missing,  missing,  missing,missing,  missing,  missing,  missing,  missing,  missing,  missing,  missing,  missing,  missing);

ArrayList sheetname = new ArrayList();

foreach (Microsoft.Office.Interop.Excel.Worksheet  sheet in wb.Sheets)
{
    sheetname.Add(sheet.Name);
}
Sub Macro1()
'
' Macro1 Macro
'

'
Dim i As Integer
For i = 1 To Sheets.Count
 Dim prefix As String
 prefix = i
 If Len(prefix) < 4 Then
  prefix = "000"
 ElseIf Len(prefix) < 3 Then
  prefix = "00"
 ElseIf Len(prefix) < 2 Then
  prefix = "0"
 End If
 Dim sheetName As String
 sheetName = Sheets(i).Name
 Dim names
 names = Split(sheetName, "-")
 If (UBound(names) > 0) And IsNumeric(names(0)) Then
  'do nothing
 Else
  Sheets(i).Name = prefix & i & "-" & Sheets(i).Name
 End If
Next

End Sub
1. Consider XLSX as a zip file. Rename *.xlsx into *.zip
2. Unzip
3. Go to unzipped folder root and open /docprops/app.xml
4. This xml contains the sheet name in the same order of what you see.
5. Parse the xml and get the sheet names
 FileStream file = new FileStream(@"yourexcelfilename", FileMode.Open, FileAccess.Read);

      HSSFWorkbook  hssfworkbook = new HSSFWorkbook(file);
        for (int i = 0; i < hssfworkbook.NumberOfSheets; i++)
        {
            Console.WriteLine(hssfworkbook.GetSheetName(i));
        }
        file.Close();
<?xml version="1.0" encoding="UTF-8" standalone="true"?>
-<Properties xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes" xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties">
<TotalTime>0</TotalTime>
<Application>Microsoft Excel</Application>
<DocSecurity>0</DocSecurity>
<ScaleCrop>false</ScaleCrop>
-<HeadingPairs>
  -<vt:vector baseType="variant" size="2">
    -<vt:variant>
      <vt:lpstr>Arbeitsblätter</vt:lpstr>
    </vt:variant>
    -<vt:variant>
      <vt:i4>4</vt:i4>
    </vt:variant>
  </vt:vector>
</HeadingPairs>
-<TitlesOfParts>
  -<vt:vector baseType="lpstr" size="4">
    <vt:lpstr>Tabelle3</vt:lpstr>
    <vt:lpstr>Tabelle4</vt:lpstr>
    <vt:lpstr>Tabelle1</vt:lpstr>
    <vt:lpstr>Tabelle2</vt:lpstr>
  </vt:vector>
</TitlesOfParts>
<Company/>
<LinksUpToDate>false</LinksUpToDate>
<SharedDoc>false</SharedDoc>
<HyperlinksChanged>false</HyperlinksChanged>
<AppVersion>14.0300</AppVersion>
</Properties>
    using System.IO.Compression;
    using System.Xml;
    using System.Xml.Linq;

    static IEnumerable<string> GetWorksheetNamesOrdered(string fileName)
    {
        //open the excel file
        using (FileStream data = new FileStream(fileName, FileMode.Open))
        {
            //unzip
            ZipArchive archive = new ZipArchive(data);

            //select the correct file from the archive
            ZipArchiveEntry appxmlFile = archive.Entries.SingleOrDefault(e => e.FullName == "docProps/app.xml");

            //read the xml
            XDocument xdoc = XDocument.Load(appxmlFile.Open());

            //find the titles element
            XElement titlesElement = xdoc.Descendants().Where(e => e.Name.LocalName == "TitlesOfParts").Single();

            //extract the worksheet names
            return titlesElement
                .Elements().Where(e => e.Name.LocalName == "vector").Single()
                .Elements().Where(e => e.Name.LocalName == "lpstr")
                .Select(e => e.Value);
        }
    }
<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
  <fileVersion appName="xl" lastEdited="5" lowestEdited="5" rupBuild="9303" /> 
  <workbookPr defaultThemeVersion="124226" /> 
- <bookViews>
  <workbookView xWindow="120" yWindow="135" windowWidth="19035" windowHeight="8445" /> 
  </bookViews>
- <sheets>
  <sheet name="By song" sheetId="1" r:id="rId1" /> 
  <sheet name="By actors" sheetId="2" r:id="rId2" /> 
  <sheet name="By pit" sheetId="3" r:id="rId3" /> 
  </sheets>
- <definedNames>
  <definedName name="_xlnm._FilterDatabase" localSheetId="0" hidden="1">'By song'!$A$1:$O$59</definedName> 
  </definedNames>
  <calcPr calcId="145621" /> 
  </workbook>
public static List<string> ToExcelsSheetList(string excelFilePath)
{
    List<string> sheets = new List<string>();
    using (OleDbConnection connection = 
            new OleDbConnection((excelFilePath.TrimEnd().ToLower().EndsWith("x")) 
            ? "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + excelFilePath + "';" + "Extended Properties='Excel 12.0 Xml;HDR=YES;'"
            : "provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + excelFilePath + "';Extended Properties=Excel 8.0;"))
    {
        connection.Open();
        DataTable dt = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
        foreach (DataRow drSheet in dt.Rows)
            if (drSheet["TABLE_NAME"].ToString().Contains("$"))
            {
                string s = drSheet["TABLE_NAME"].ToString();
                sheets.Add(s.StartsWith("'")?s.Substring(1, s.Length - 3): s.Substring(0, s.Length - 1));
            }
        connection.Close();
    }
    return sheets;
}