I have a number of word documents I am converting. Everything is going great until I get a file that is read only. In this case I get a Save As prompt.
Is there any way to open the file in read/write format? I should have admin privileges so access isn't an issue.
I'm using VB.net to open the files. More specifically
doc = word.Documents.Open(path, Type.Missing, False, 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)
To open a read-only file you need to set that attribute to false:
string path = "C:\\test.txt";
FileInfo info = new FileInfo(path);
info.IsReadOnly = false;
StreamWriter writer = new StreamWriter(path);
writer.WriteLine("This is an example.");
writer.Close();
info.IsReadOnly=true;
This was an example but I'm sure it will work with word files.
EDIT:
VB.NET equivalent:
Dim path As String = "C:\test.txt"
Dim info As FileInfo = New FileInfo(path)
info.IsReadOnly = False
Dim writer As StreamWriter = New StreamWriter(path)
writer.WriteLine("This is an example.")
writer.Close()
info.IsReadOnly = True
Before you open the file, check its Attributes with a FileInfo class.
If the Attributes property contains FileAttributes.ReadOnly, change it and the file will no longer be read-only.
Related
I need to convert an XLSX file to another CSV file.
I've done a lot of research on how to do this process, but I did not find anything that suited me.
I found this Github Gist only Convert an Epplus ExcelPackage to a CSV file
That returns an Array of binary. But apparently it does not work any more.
I'm trying to load Array using LoadFromCollection
FileInfo novoArquivoCSV = new FileInfo(fbd.SelectedPath);
var fileInfoCSV = new FileInfo(novoArquivo + "\\" + nameFile.ToString() + ".csv");
using (var csv = new ExcelPackage(fileInfoCSV))
{
csv.Workbook.Worksheets.Add(nameFile.ToString());
var worksheetCSV = csv.Workbook.Worksheets[1];
worksheetCSV.Cells.LoadFromCollection(xlsx.ConvertToCsv());
}
The code you linked to reads an XLSX sheet and returns the CSV data as a byte buffer through a memory stream.
You can write directly to a file instead, if you remove the memory stream and pass the path to the target file in ConvertToCsv :
public static void ConvertToCsv(this ExcelPackage package, string targetFile)
{
var worksheet = package.Workbook.Worksheets[1];
var maxColumnNumber = worksheet.Dimension.End.Column;
var currentRow = new List<string>(maxColumnNumber);
var totalRowCount = worksheet.Dimension.End.Row;
var currentRowNum = 1;
//No need for a memory buffer, writing directly to a file
//var memory = new MemoryStream();
using (var writer = new StreamWriter(targetFile,false, Encoding.UTF8))
{
//the rest of the code remains the same
}
// No buffer returned
//return memory.ToArray();
}
Encoding.UTF8 ensures the file will be written as UTF8 with a Byte Order Mark that allows all programs to understand this is a UTF8 file instead of ASCII. Otherwise, a program could read the file as ASCII and choke on the first non-ASCII character encountered.
Checkout the .SaveAs() method in Excel object.
wbWorkbook.SaveAs("c:\yourdesiredFilename.csv", Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV)
Or following:
public static void SaveAs()
{
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.ApplicationClass();
Microsoft.Office.Interop.Excel.Workbook wbWorkbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel.Sheets wsSheet = wbWorkbook.Worksheets;
Microsoft.Office.Interop.Excel.Worksheet CurSheet = (Microsoft.Office.Interop.Excel.Worksheet)wsSheet[1];
Microsoft.Office.Interop.Excel.Range thisCell = (Microsoft.Office.Interop.Excel.Range)CurSheet.Cells[1, 1];
thisCell.Value2 = "This is a test.";
wbWorkbook.SaveAs(#"c:\one.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
wbWorkbook.SaveAs(#"c:\two.csv", Microsoft.Office.Interop.Excel.XlFileFormat.xlCSVWindows, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
wbWorkbook.Close(false, "", true);
}
Is there any simple way to convert .xls file to .csv file? (Excel)
There are several other resources online that can help with this ind of thing. Actually, for something generic like this, you should always Google for a solution, and try to figure it out yourself. That's the best way to learn how to do technical things. If you get stuck, or if you have a very specific question, this site is a great place to post your question(s). It seems to me, you probably started here, and you didn't do any preliminary work yourself.
I am using the below piece of code to add hyperlink to a given cell("A1" here):
Workbook workbook = _excelApp.Workbooks.Open("C:\\temp\\test1.xlsx",
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);
Worksheet worksheet = (Worksheet)workbook.Worksheets[1];
Range rangeToHoldHyperlink = worksheet.get_Range("A1", Type.Missing);
string hyperlinkTargetAddress = "www.bing.com";
Range excelRange = worksheet.UsedRange;
object[,] valueArray = (object[,])excelRange.get_Value(
XlRangeValueDataType.xlRangeValueDefault);
worksheet.Hyperlinks.Add(
rangeToHoldHyperlink,
hyperlinkTargetAddress,
string.Empty,
string.Empty,
valueArray[1, 1].ToString());
It adds the hyperlink. But, on clicking it, it says:
Reference not valid
On hovering the mouse over cell text, it displays the hyperlink as:
excel_file_path\hyperlinkTargetAddress
Why it is doing so?
How this can be overcome?
You can add different types of hyperlinks. By default, Excel assumes that you want to link a file in your hard drive (in the folder where the spreadsheet it). To tell Excel that you want a website, you have to write the full address (with the starting http:// bit).
string hyperlinkTargetAddress = "http://www.bing.com";
I have a program that I need to maintain ( was not written by me)
What the actual function is doing is that it gets an excel file from the internet and then convert it to html (I don't even know why) then it tries to save it into a new csv file...
Long story short, my problem in the whole code resides in these 2 parts
xl = new Microsoft.Office.Interop.Excel.Application();
xl.Visible = false;
//p_sUBKPath is the path of the HTML file that has the converted excel file
Microsoft.Office.Interop.Excel.Workbook workbook = xl.Workbooks.Open(p_sUBKPath, 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);
Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[1];
Microsoft.Office.Interop.Excel.Range range = ws.UsedRange;
object[,] values = (object[,])range.Value2;
The code has an if statement that try to ensure that every values from the first row in the html matches values required
if (Convert.ToString(values[1, 1]).ToUpper().Trim() == "DOMAIN NAME" && values[1, 2]).ToUpper().Trim() == "SHORT NAME" && values[1,3]).ToUpper().Trim() == "LONG NAME" )
{
//do something
}
The if statement is returning true and jumping to else statement, after few debugging and trying some lines of code it turned out that values[1,2] and values[1,3] are returning out of array boundary error.
and the value of values[1,1] is the whole row which contains DOMAIN NAME, SHORT NAME, AND LONG NAME, so even this statement returns flase
if (Convert.ToString(values[1, 1]).ToUpper().Trim() == "DOMAIN NAME")
{
//do something
}
Any idea what is happening in the code?
I have a requirement to modify the ms project file (.mpp) using C#.net.
I have done with all the things, the only thing remaining is to modify the TimescaleStart date of MPP file using C#.net. I need to set the user defined date.
How can i do that?
Following is my code:
Microsoft.Office.Interop.MSProject.Application app = new Microsoft.Office.Interop.MSProject.Application();
app.DisplayAlerts = false;
app.AskToUpdateLinks = false;
app.FileOpenEx(
strFilePath + "test.mpp",
false,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
PjPoolOpen.pjPoolReadWrite, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
Microsoft.Office.Interop.MSProject.Project pj = app.ActiveProject;
object objDate = dt.Date;
app.TimescaleStart = objDate;
Got Error as
Type mismatch. (Exception from HRESULT: 0x80020005
(DISP_E_TYPEMISMATCH))
on Following line:
app.TimescaleStart = objDate;
Could it be that you're actually trying to change the project start date?
If that's the case, try using the "ProjectMove" method.
reference here and here.
If you really really want to change TimescaleStart, it looks like you are out of luck.
TimescaleStart is a read-only property which returns the date that the timescale starts in the current view.
If you want to scroll the view so that it starts at a certain date, find a task with a start date on or close to your target date, select it and invoke the GotoTaskDates method of the application object. For example:
app.Find "Start", "is greater than or equal to", "1/1/2014", Type.Missing, Type.Missing, Type.Missing, Type.Missing
app.GotoTaskDates
Update:
If you are using Project 2010 or later, you can also use this method:
app.PanZoomPanTo (objDate)
I'm using Excel 2010.
I'm trying so save my excel file, with this code.
It does save a .xls file, but when I open the file I get this message:
The file you are trying to open, 'tre.xls', is in a different format than specified by the file extension. Verify that the file is not corrupted and is from a thrusted source before opening the file. Do you want to open the file now?
If I press yesthe file opens. But what do I need to get rid of this format-popup?
My code:
using System;
using System.Windows.Forms;
using ExcelAddIn1.Classes;
using ExcelAddIn1.Classes.Config;
using Microsoft.Office.Interop.Excel;
using Application = Microsoft.Office.Interop.Excel.Application;
using System.Runtime.InteropServices;
private void Foo(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.FileName = null;
saveFileDialog.Title = "Save path of the file to be exported";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
// Save.
// The selected path can be got with saveFileDialog.FileName.ToString()
Application excelObj =
(Application)Marshal.GetActiveObject("Excel.Application");
Workbook wbook = excelObj.ActiveWorkbook;
wbook.SaveAs(saveFileDialog.FileName, XlFileFormat.xlWorkbookDefault,
Type.Missing, Type.Missing, false, false,
XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing);
wbook.Close();
}
}
When I save in excel in the normal way I get "Book1.xlsx", that have no problem to open.
============= FINAL SOLUTION ============
private void Foo(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.FileName = null;
saveFileDialog.Title = "Save path of the file to be exported";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
Application excelObj = (Application)Marshal.GetActiveObject("Excel.Application");
Activate(); // <-- added (recommend by msdn, but maybe not nessary here)
Workbook wbook = excelObj.ActiveWorkbook;
wbook.SaveAs(saveFileDialog.FileName, XlFileFormat.xlExcel8, Type.Missing,
Type.Missing, false, false, XlSaveAsAccessMode.xlNoChange, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing);
// wbook.Close(); // <-- don't want this anymore
}
}
With your code you save the workbook as Open XML because XlFileFormat.xlWorkbookDefault evaluates to XlFileFormat.xlOpenXMLWorkbook for Excel 2007+. This is the reason of the warning: you named the file as XLS but actually it is a XLSX.
You can change the file extension to xlsx in your saveFileDialog.Filter property or force the Excel object to save in the XLS format using XlFileFormat.xlExcel8.
EDIT
Use this to save your document:
wbook.SaveAs(saveFileDialog.FileName, XlFileFormat.xlExcel8,
Type.Missing, Type.Missing, false, false,
XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing);
try to set alerts to OFF
oExcel.DisplayAlerts = false;
This problem results from a feature called Extension Hardening, and you can find more information about it here.
Unfortunately, the link above also states that there are no expected changes to this code until at least Office 14.
If you don’t want to look for a solution, but just want to solve the problem, insert this key in your registry to suppress the notification:
[HKEY_CURRENT_USER\Software\Microsoft\Office\12.0\Excel\Security] “ExtensionHardening”=dword:00000000
You can accomplish the above by doing the following:
Open your Registry (Start -> Run -> regedit.exe).
Navigate to HKEY_CURRENT_USER\SOFTWARE\MICROSOFT\OFFICE\12.0\EXCEL\SECURITY.
Right click in the right window and choose New -> DWORD
Type “ExtensionHardening” as the name (without the quotes)
Verify that the data has the value “0″.