I have small application where user at the end can save the results in excel file. Everything looks fine but a few seconds after this appear Microsoft Windows communicate: "Program Microsoft Office Excel stop working". Ok - ingoring it.
If user saves data as *.xls file there is no problem to open this file - data saved into this file are correct.
If user saves data as *.xlsx file ther is a problem. When I try to open this file there show me message: "Program Microsoft Excel can't open file *.xlsx because there is wrong file format or extension. Check if the file was damaged and if the file extension is correct with his format".
The code that I use to save data as excel file are below:
public void SaveData(ExcelWriter ew)
{
SaveFileDialog saveFD = new SaveFileDialog();
saveFD.InitialDirectory = "C:\\users\\Documents";
saveFD.FileName = this._saveExcelFileName;
saveFD.Filter = "excel 97-03(*.xls)|*.xls|excel 2007 (*.xlsx)|*.xlsx";
saveFD.FilterIndex = 2;
saveFD.RestoreDirectory = true;
if (saveFD.ShowDialog() == DialogResult.OK)
{
try
{
this._saveExcelFileName = saveFD.FileName;
ew.RunExcelWriter(_dt, _saveExcelFileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
public void RunExcelWriter(DataTable DataT, string fileName)
{
StartExcel();
GetANewWorkbook();
GetTheActiveSheet();
ProcessTheDataTable(DataT);
SaveTheSheet(fileName);
Clean();
}
private void StartExcel()
{
// Start Excel and get Application object.
oXL = new Excel.Application();
// Set some properties
oXL.Visible = true;
oXL.DisplayAlerts = false;
}
private void GetANewWorkbook()
{
// Get a new workbook.
oWB = oXL.Workbooks.Add(Missing.Value);
}
private void GetTheActiveSheet()
{
oSheet = (Excel.Worksheet)oWB.ActiveSheet;
oSheet.Name= "Wyniki";
}
private void ProcessTheDataTable(DataTable DT)
{
int rowCount = 1;
foreach (DataRow dr in DT.Rows)
{
rowCount += 1;
for (int i = 1; i < DT.Columns.Count + 1; i++)
{
// Add the header the first time through
if (rowCount == 2)
{
oSheet.Cells[1, i] = DT.Columns[i - 1].ColumnName;
}
oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
}
}
// Resize the columns
oRange = oSheet.get_Range(oSheet.Cells[1, 1], oSheet.Cells[rowCount, DT.Columns.Count]);
oRange.EntireColumn.AutoFit();
//oRange.Style = oSheet.Cells.Style;
}
private void SaveTheSheet(string FN)
{
oSheet = null;
oRange = null;
oWB.SaveAs(FN, Excel.XlFileFormat.xlWorkbookNormal,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Excel.XlSaveAsAccessMode.xlShared,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
if(oWB.Saved==true)
{
MessageBox.Show("Plik został zapisany pomyślnie");
}
else
{
MessageBox.Show("PLIKU NIE ZAPISANO");
}
oWB.Close(Missing.Value, Missing.Value, Missing.Value);
oWB = null;
oXL.Quit();
}
If anyone knows why this happens?
Many thanks in advance
Update 1:
The suggested answer didn't work. I change to the following:
private void SaveTheSheet(string FN)
{
oSheet = null;
oRange = null;
oWB.SaveAs(FN, Excel.XlFileFormat.xlXMLSpreadsheet,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Excel.XlSaveAsAccessMode.xlShared,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
if(oWB.Saved==true)
{
MessageBox.Show("Plik został zapisany pomyślnie");
}
else
{
MessageBox.Show("PLIKU NIE ZAPISANO");
}
oWB.Close(Missing.Value, Missing.Value, Missing.Value);
oWB = null;
oXL.Quit();
}
Now when I saving there is a meesage:
"Exception from HRESULT: 0x800A03EC
Update 2:
I struggled a little bit yesterday and I managed to get the desired effect when writing data to the .xlsx format. When saving to .xls I still get the Microsoft Windows message to close the excel application, but at least (after the approval of another warning) I can open this file.
Below code which I'm using to saving to .xlsx format:
oWB.SaveAs(FN, Excel.XlFileFormat.xlWorkbookDefault,
Missing.Value, Missing.Value, false, false,
Excel.XlSaveAsAccessMode.xlNoChange,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
Here is to .xls
oWB.SaveAs(FN, Excel.XlFileFormat.xlXMLSpreadsheet,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Excel.XlSaveAsAccessMode.xlNoChange,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
Please - any advice is important.
In my case aslo works Excel.XlFileFormat.xlWorkbookDefault and Excel.XlFileFormat.xlOpenXMLWorkbook
oWB.SaveAs(fileName, Excel.XlFileFormat.xlOpenXMLWorkbook, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
or
oWB.SaveAs(fileName, Excel.XlFileFormat.xlWorkbookDefault, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
When saving as an .xslx, try using Excel.xlXMLSpreadsheet instead of Excel.XlFileFormat.xlWorkbookNormal
Related
I want to fetch an image from an external site and save it on the web application´s server.
My current code downloads the file, but it won't open because of wrong format, it says.
private Uri _uri;
private HttpClient _client;
[HttpPost]
public async Task WmsExport(ExportImagePostData postData)
{
try
{
PrepareUri(postData);
ValidateUrl(postData);
PrepareRequest(postData);
await FetchImageAndSave_async(postData);
}
catch (TaskCanceledException)
{
HttpContext.Response.StatusCode = 408;
}
catch (Exception ex)
{
var statusCode = 500;
HttpContext.Response.StatusCode = statusCode;
_logger.LogError(ex, ex.Message);
}
}
private void PrepareRequest(ExportImagePostData postData)
{
_client = _customClientFactory.CreateHttpClient();
_client.BaseAddress = _uri;
_client.CopyRequestHeaders(HttpContext);
_client.DefaultRequestHeaders.Add("Accept", "image/png");
}
public async Task FetchImageAndSave_async(ExportImagePostData postData)
{
using (var contentStream = await _client.GetStreamAsync(_client.BaseAddress.OriginalString))
{
await SaveImageOnServer_async(postData, contentStream);
}
}
private async Task SaveImageOnServer_async(ExportImagePostData postData, Stream downloadStream)
{
var filename = "wmsexp" + DateTime.Now.ToString("HHmm") + "." + postData.ImageType;
var directory = "wwwroot/Images/uploads/";
var path = Path.Combine(Directory.GetCurrentDirectory(), directory, filename);
using (var outStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 1048576, true))
{
await downloadStream.CopyToAsync(outStream);
}
}
Here is how the images look like in my folder, when I try to open them:
****SOLVED** **
I got help from Roman Marusyk, here on Stack Overflow. Thanks Roman! If you write an answer I be happy to set it as the answer!
The issue seem to have been that I added wrong HTTP-headers, and that some of my paths to the images where incorrect.
I have tried to read IMB barcode from an image with the below code snippet, but it always return null. I have also tried with the IMB barcode images in the blackbox testing below, but doesn't work.
https://github.com/micjahn/ZXing.Net/tree/master/Source/test/data/blackbox/imb-1
private static void Decode()
{
Bitmap bitmap = new Bitmap(#"\07.png");
try
{
MemoryStream memoryStream = new MemoryStream();
bitmap.Save(memoryStream, ImageFormat.Bmp);
byte[] byteArray = memoryStream.GetBuffer();
ZXing.LuminanceSource source = new RGBLuminanceSource(byteArray, bitmap.Width, bitmap.Height);
var binarizer = new HybridBinarizer(source);
var binBitmap = new BinaryBitmap(binarizer);
IMBReader imbReader = new IMBReader();
Result str = imbReader.decode(binBitmap);
}
catch { }
}
I have solved this problem by using the below code snippet shared through the below link.
https://github.com/micjahn/ZXing.Net/issues/59
private static void Decode2()
{
var bitmap = new Bitmap(#"\07.png"); // make sure that the file exists at the root level
try
{
var imbReader = new BarcodeReader
{
Options =
{
PossibleFormats = new List<BarcodeFormat> {BarcodeFormat.IMB}
}
};
var result = imbReader.Decode(bitmap);
if (result != null)
System.Console.WriteLine(result.Text);
else
System.Console.WriteLine("nothing found");
}
catch (System.Exception exc)
{
System.Console.WriteLine(exc.ToString());
}
}
Everything is setup well (call method, .xsd file, rdlc file, when i do debugging I can see data in my model, I can download the excel file, but it is still remining empty?! Wher did I'm wrong in my code? Any clue?
My ActionResult in Controller:
[HttpGet]
public ActionResult Export_StudentStatus()
{
List<pr_ReportDataGenerate_AllGeneralOverview_Result> model = Context.pr_ReportDataGenerate_AllGeneralOverview().Where(p => p.rdTypeID == 2).ToList();
ReportViewer viewer = new ReportViewer();
try
{
Warning[] warnings;
string[] streamIds;
string mimeType = string.Empty, encoding = string.Empty, extension = string.Empty;
viewer.ProcessingMode = ProcessingMode.Local;
//viewer.LocalReport.EnableExternalImages = true;
viewer.LocalReport.ReportPath = Server.MapPath("~/RDLC/GeneralOverviewStudentStatus.rdlc");
viewer.LocalReport.DataSources.Add(new ReportDataSource("dsGeneralOverviewAnnualAwards", model));//ova e DS vo reportot
viewer.LocalReport.EnableHyperlinks = true;
byte[] bytes = viewer.LocalReport.Render("Excel", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
Response.Clear();
Response.ContentType = mimeType;
Response.AddHeader("content-disposition", "attachment; filename=GeneralOverviewStudentStatus.xls");
Response.BinaryWrite(bytes);
Response.End();
return null;
}
finally
{
if (viewer != null)
{
viewer.Dispose();
viewer = null;
}
}
}
I am trying to read a text file from IsolatedStorage and check it contains a string. If not, the string is added to the end of the file. But When I am trying to write the string into file I got an error: "Operation not permitted on IsolatedStorageFileStream.". My code shown below. How can I overcome this problem?
public void AddToDownloadList()
{
IsolatedStorageFile downloadFile=IsolatedStorageFile.GetUserStoreForApplication();
try
{
string downloads = string.Empty;
if (!downloadFile.DirectoryExists("DownloadedFiles"))
downloadFile.CreateDirectory( "DownloadedFiles" );
if(downloadFile.FileExists("DownloadedFiles\\DownloadList.txt"))
{
IsolatedStorageFileStream downloadStream = downloadFile.OpenFile("DownloadedFiles\\DownloadList.txt",FileMode.Open, FileAccess.Read );
using ( StreamReader reader = new StreamReader( downloadStream ) )
{
downloads = reader.ReadToEnd();
reader.Close();
}
downloadFile.DeleteFile( "DownloadedFiles\\DownloadList.txt" );
}
downloadFile.CreateFile( "DownloadedFiles\\DownloadList.txt" );
string currentFile = FileName;
if ( !downloads.Contains( currentFile ) )
{
downloads += currentFile;
using ( StreamWriter writeFile = new StreamWriter( new IsolatedStorageFileStream( "DownloadedFiles\\DownloadList.txt", FileMode.Create, FileAccess.Write, downloadFile ) ) )
{
writeFile.Write( currentFile + "," );
writeFile.Close();
}
}
}
catch ( Exception ex )
{
string message = ex.Message;
}
}
I think the problem you were having has to do with the line where you create the StreamWriter by newing up the IsolatedStorageFileStream - when you already should have the right one from the return of the downloadFile.CreateFile() call.
Try this code, I think it does what you want to do:
public static void AddToDownloadList()
{
try
{
AddToDownloadList("DownloadedFiles", "this file name", "DownloadedFiles\\DownloadList.txt");
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Exception: " + ex.Message);
}
}
public static void AddToDownloadList(string directory, string fileName, string filePath)
{
string downloads = string.Empty;
using (IsolatedStorageFile downloadFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!downloadFile.DirectoryExists(directory))
downloadFile.CreateDirectory(directory);
if (downloadFile.FileExists(filePath))
{
IsolatedStorageFileStream downloadStream = downloadFile.OpenFile(filePath, FileMode.Open, FileAccess.Read);
using (StreamReader reader = new StreamReader(downloadStream))
{
downloads = reader.ReadToEnd();
reader.Close();
}
}
string currentFile = fileName;
if (!downloads.Contains(currentFile))
{
downloadFile.DeleteFile(filePath);
using (IsolatedStorageFileStream stream = downloadFile.CreateFile(filePath))
{
downloads += currentFile;
using (StreamWriter writeFile = new StreamWriter(stream))
{
writeFile.Write(currentFile + ",");
writeFile.Close();
}
}
}
}
}
I need to download jpeg image and show it in my midlet.
But when I try to run this code, image on screen is broken.
What is wrong?
public void startApp() {
HttpConnection conn = null;
InputStream is = null;
try {
conn = (HttpConnection) Connector.open("http://av.li.ru/227/2374227_8677578.jpg", Connector.READ, false);
conn.setRequestMethod( HttpConnection.GET);
int rc = conn.getResponseCode();
if (rc != HttpConnection.HTTP_OK) {
throw new Exception("ResponseCode = " + rc);
}
is = conn.openDataInputStream();
byte []b = new byte[(int) conn.getLength()];
is.read(b);
Image img = Image.createImage(b, 0, b.length);
Form f = new Form("test");
f.append(img);
Display.getDisplay(this).setCurrent(f);
} catch (Exception e) {
}
}
Thanks