簡體   English   中英

Excel Open錯誤:創建Excel時“發現不可讀的內容”

[英]Excel Open error: “found unreadable content” when creating Excel

我收到錯誤消息:“ Excel在APPL_1.xlsx中發現了不可讀的內容。” 我的代碼有什么問題?

記錄包含大約2個缺少數據。 我試圖從數據表中獲取它到excel。

我正在使用OpenXMLSpreedsheetDocument從數據表中獲取數據到excel

            FileInfo FileLoc = new FileInfo(FilePath);
            if (FileLoc.Exists)
            {
                FileLoc.Delete();
                FileLoc = new FileInfo(FilePath);
            }
            SpreadsheetDocument spreadSheet = SpreadsheetDocument.
            Create(FilePath, SpreadsheetDocumentType.Workbook);

            // Add a WorkbookPart to the document.
            WorkbookPart workbookpart = spreadSheet.AddWorkbookPart();
            workbookpart.Workbook = new Workbook();

            // Add a WorksheetPart to the WorkbookPart.
            var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
            var sheetData = new SheetData();
            worksheetPart.Worksheet = new Worksheet(sheetData);

            var bold1 = new Bold();
            CellFormat cf = new CellFormat();

            // Add Sheets to the Workbook.
            Sheets sheets;
            sheets = spreadSheet.WorkbookPart.Workbook.
                AppendChild<Sheets>(new Sheets());

            // Append a new worksheet and associate it with the workbook.
            var sheet = new Sheet()
            {
                Id = spreadSheet.WorkbookPart.
                    GetIdOfPart(worksheetPart),
                SheetId = 0,
                Name = "Sheet" + 0
            };
            sheets.Append(sheet);

            //Add Header Row.
            var headerRow = new Row();
            foreach (DataColumn column in dt.Columns)
            {
                var cell = new Cell
                {
                    DataType = CellValues.String,
                    CellValue = new CellValue(column.ColumnName)
                };
                headerRow.AppendChild(cell);
            }
            sheetData.AppendChild(headerRow);
            foreach (DataRow row in dt.Rows)
            {
                var newRow = new Row();
                foreach (DataColumn col in dt.Columns)
                {
                    Cell c = new Cell();
                    c.DataType = new EnumValue<CellValues>(CellValues.String);
                    c.CellValue = new CellValue(row[col].ToString());
                    newRow.Append(c);
                }
                sheetData.AppendChild(newRow);
            }
            workbookpart.Workbook.Save();
            ProcessStartInfo startInfo = new ProcessStartInfo(FilePath);
            Process.Start(startInfo);  

任何建議都非常感謝..!

這是我對OpenXML的實現。 為簡單起見,我已排除了單元樣式代碼。

這將創建一個具有兩行三列的excel文件。 您可以修改它以滿足您的需求。

主要方法:

static void Main(string[] args)
{
    var dtToXl = new DtToExcel();
    var dt = new DataTable();
    dt.Columns.Add("Col1");
    dt.Columns.Add("Col2");
    dt.Columns.Add("Col3");
    dt.Rows.Add("R1C1", "R1C2", "R1C3");
    dt.Rows.Add("R2C1", "R2C2", "R2C3");

    dtToXl.GetExcel(dt);
    if(Debugger.IsAttached)
    {
        Console.ReadLine();
    }
}

GetExcel方法:

public void GetExcel(DataTable dt)
{
    using (var document = SpreadsheetDocument.Create("C:\\Desktop\\Excel1.xlsx", SpreadsheetDocumentType.Workbook))
    {
        var workbookPart = document.AddWorkbookPart();
        workbookPart.Workbook = new Workbook();
        var sheets = workbookPart.Workbook.AppendChild(new Sheets());
        AddWorksheet(dt, 1, ref sheets, ref workbookPart);
    }
}

AddWorksheet方法:

private void AddWorksheet(DataTable dt, int sheetCount, ref Sheets sheets, ref WorkbookPart workbookPart)
{
    var worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
    var sheetData = new SheetData();
    var sheetName = $"Sheet{sheetCount}";
    worksheetPart.Worksheet = new Worksheet();

    //Create header rows
    #region Excel Headers
    Row row = new Row
    {
        RowIndex = 1
    };
    row.AppendChild(AddCellWithValue("Column 1", CellValues.InlineString));
    row.AppendChild(AddCellWithValue("Column 2", CellValues.InlineString));
    row.AppendChild(AddCellWithValue("Column 3", CellValues.InlineString));
    sheetData.AppendChild(row);
    #endregion

    //Create data rows
    #region Excel data rows
    var rowIndex = (UInt32)2;
    foreach (DataRow dtRow in dt.Rows)
    {
        row = new Row
        {
            RowIndex = rowIndex++
        };
        row.AppendChild(AddCellWithValue(dtRow[0].ToString(), CellValues.InlineString));
        row.AppendChild(AddCellWithValue(dtRow[1].ToString(), CellValues.InlineString));
        row.AppendChild(AddCellWithValue(dtRow[2].ToString(), CellValues.InlineString));
        sheetData.AppendChild(row);
    }
    #endregion

    var columns = new Columns();
    columns.Append(new Column() { Min = 1, Max = 1, Width = 20, CustomWidth = true });
    columns.Append(new Column() { Min = 2, Max = 2, Width = 20, CustomWidth = true });
    columns.Append(new Column() { Min = 3, Max = 3, Width = 20, CustomWidth = true });

    worksheetPart.Worksheet.Append(columns);
    worksheetPart.Worksheet.Append(sheetData); //This line should be anywhere below .Append(columns)

    var sheet = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = (UInt32)sheetCount, Name = sheetName };
    sheets.Append(sheet);
}

AddCellWithValue方法

private Cell AddCellWithValue(string value, CellValues type)
{
    var cell = new Cell
    {
        DataType = type
    };
    if (type == CellValues.InlineString)
    {
        var inlineString = new InlineString();
        var t = new Text
        {
            Text = value
        };
        inlineString.AppendChild(t);
        cell.AppendChild(inlineString);
    }
    else
    {
        cell.CellValue = new CellValue(value);
    }
    return cell;
}

我用過SpreadsheetLight。

這是我的代碼。

            using SpreadsheetLight;

            SLDocument sl = new SLDocument();

            int iStartRowIndex = 1;
            int iStartColumnIndex = 1;

            sl.ImportDataTable(iStartRowIndex, iStartColumnIndex, dt, true);

            // + 1 because the header row is included
            // - 1 because it's a counting thing, because the start row is counted.
            int iEndRowIndex = iStartRowIndex + dt.Rows.Count + 1 - 1;
            // - 1 because it's a counting thing, because the start column is counted.
            int iEndColumnIndex = iStartColumnIndex + dt.Columns.Count - 1;

            SLTable table = sl.CreateTable(iStartRowIndex, iStartColumnIndex, iEndRowIndex, iEndColumnIndex);
            table.SetTableStyle(SLTableStyleTypeValues.Medium17);
            table.HasTotalRow = true;
            table.SetTotalRowFunction(5, SLTotalsRowFunctionValues.Sum);
            sl.InsertTable(table);

            sl.SaveAs(FilePath);
            sl.Dispose();
            ProcessStartInfo startInfo = new ProcessStartInfo(FilePath);
            Process.Start(startInfo);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM